[go: up one dir, main page]

0% found this document useful (0 votes)
28 views96 pages

Python Mod 3

digital logic architectue

Uploaded by

abhishek5274n2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
28 views96 pages

Python Mod 3

digital logic architectue

Uploaded by

abhishek5274n2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 96
Python Programming Course Code : CSE3011 Course Cred Course Type : LP Dr. Pranshu Pranjal (MTech & PhD, IIT (/SM) Dhanbad) Assistant Professor (AB 125/122) Division - Artificial Intelligence & Machine Learning, ‘School of Computing Science and Engineering, VIT Bhopal University, Bhopal-indore Highway, Kothrikalan, Sehore, Madhya Pradesh - 466114 Contact No.: {M} (+91) 897960032 Email: pranshupranjal@vitbhopal.ac.in Module 3 Principles of Object Orientation Classes in Python, Creating Classes Instance Methods Access Specification Data modeling, Persistent storage of objects Inheritance, polymorphism and operator overloading Abstract classes Exception handling, try block Object-oriented programming + OOP is an abbreviation that stands for Object-oriented programming paradigm. It is defined as a programming model that uses the concept of objects which refers to real-world entities with state and behavior. + Python is a programming language that supports object-oriented programming. This makes it simple to create and use classes and objects Procedural Oriented Approach + Early programming languages developed in 50s and 60s are recognized as procedural (or procedure oriented) languages. + Acomputer program describes procedure of performing certain task by writing a series of instructions in a logical order, Logic of a more complex program is broken down into smaller but independent and reusable blocks of statements called functions. + Every function is written in such a way that it can interface with other functions in the program. Data belonging toa function can be easily shared with other in the form of arguments, and called function can return its result back to calling function. Prominent problems related to procedural approach are as follows — Its top-down approach makes the program difficult to maintain * It uses a lot of global data items, which is undesired. Too many global data items would increase memory overhead. * It gives more importance to process and doesn't consider data of same importance and takes it for granted, thereby it moves freely through the program. + Movement of data across functions is unrestricted, In real-life scenario where there is unambiguous association of a function with data it is expected to process. OOP Concepts In the real world, we deal with and process objects, such as student, employee, invoice, car, etc. Objects are not only, data and not only functions, but combination of both. Each real-world object has attributes and behavior associated with it. class CAR Properties Methods Ford Properties Properties Methods Methods Attributes + Name, class, subjects, marks, etc,, of student + Name, designation, department, salary, etc., of employee Invoice number, customer, product code and name, price and quantity, etc,, in an invoice + Registration number, owner, company, brand, horsepower, speed, etc., of car Behavior Processing attributes associated with an object. + Compute percentage of student's marks + Calculate incentives payable to employee + Apply GST to invoice value + Measure speed of car > Behavior is equivalent to function. In real life, attributes and behavior are not independent of each other, rather they co-exist. > The most important feature of object-oriented approach is defining attributes and their functionality as a single unit called class. It serves as a blueprint for all objects having similar attributes and behavior, > In OOP, class defines what are the attributes its object has, and how is its behavior. Object, on the other hand, is an instance of the class. Principles of OOPs Concepts Object-oriented programming paradigm is characterized by the following principles - Class Object Encapsulation co Inheritance Polymorphism Principles of ‘oop Class. user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation. Object: An individual object of a certain class. An object that belongs to a class Circle, for example, is an instance of the class Circle. A unique instance of a data structure that is defined by its class. An object comprises both data members (class variables and instance variables) and methods, Encapsulation: Data members of class are available for processing to functions defined within the class only. Functions of class on the other hand are accessible from outside class context. So object data is hidden from environment that is external to class. Class function (also called method) encapsulates object data so that unwarranted access to it is prevented. Inheritance: A software modelling approach of OOP enables extending capability of an existing class to build new class instead of building from scratch. In OOP terminology, existing class is called base or parent class, while new class is called child or sub class. Child class inherits data definitions and methods from parent class. This facilitates reuse of features already available. Child class can add few more definitions or redefine a base class function. Polymorphism: Polymorphism is a Greek word meaning having multiple forms, In OOP, polymorphism occurs when each sub class provides its own implementation of an abstract method in base class. Classes and Objects + Aclass is a user-defined blueprint or prototype from which objects are created. + Classes provide a means of bundling data and functionality together. + Creating a new class creates a new type of abject, allowing new instances of that type to be made, + Each class instance can have attributes attached to it for maintaining its state. + Class instances can also have methods (defined by their class) for modifying their state. + In python, a private variable is defined by defining a variable and prefixing its name with a single underscore (_) ‘To understand the need for creating a class and object in Python... + let's consider an example, let’s say you wanted to track the number of dogs that may have different attributes like breed and age. Ifa list is used, the first element could be the dog’s breed while the second element could represent its age. + Let’s suppose there are 100 different dogs, then how would you know which element is supposed to be which? What if you wanted to add other properties to these dogs? This lacks organization and it’s the exact need for classes, Syntax: Class Definition class ClassName: # Statement Syntax: Object Definition obj = ClassName() print (obj.atrr) ‘The class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object. Some points on Python class: + Classes are created by keyword class. + Attributes are the variables that belong to a class. + Attributes are always public and can be accessed using the dot (.) operator. Eg.: My class.Myattribute Python Classes/Objects Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. + AClass is like an object constructor, or a "blueprint" for creating objects. Create a Class To create a class, use the keyword class: Example class MyClass Create a class named MyClass, with a property named x: = Create Object Now we can use the class named MyClass to create objects: Example pl = MyClass() Create an object named p1, and print the value of x print(p1.x) Example of Python Class and object Creating an object in Python involves instantiating a class to create a new instance of that class. This process is also referred to as object instantiation. In the example, an object is created which is basically a dog named Rodger. This class only has ‘two class attributes that tell us that Rodger is a dog and a mammal In this example, we are creating a Dog class and we have created two class variables attri and attr2.. We have created a method named fun() which returns the string “I’m a, {attr1}” and I'm a, {attr2} We have created an object of the Dog class and we are printing at the attr1 of the object. Finally, we are calling the fun() function t mammal I'm a mammal I'm a dog % Python3 program to fa class - class 00g: #A stuple class attra = "manmal” attr = “dog” # A sample method def fun(selt) print("r'm a*, self.attr1) print("I'm a", self.attr2) er code Rodger = Dog() # accessing class attributes # and method through objects print Rodger .attr1) Rodger. fun() Self Parameter + The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class: Example Use the words mysillyobject and abc instead of self: class Person: def __init__(mysillyobject, name, age): mysillyobject name = name ysillyobject.age = age def myfunc(abe): print("Hello my name is " + abc.name) pl = Person("John", 36) pi.myfunc() Hello my name is John ‘When we call a method of this object as myobject.method{arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) - this is all the special self is about. Example: Parameter class Gre: | — def _ init__(self, name, company): | self_name=name Property|. Soe self. company = company Method || def show(self): _ l obj = GFG{"Iohn", “VIT") obj.show() print("Hello my name is" + self_name +" and | work in "+ self_company +".") Private Variable ‘The Self Parameter does not call it to be Self, You can use any other name instead of it. Here we change the self to the word someone and the output will be the same. class GFG: def __init_(somename, name, company): somename.name = name somename.company = company def show(somename} print("Hello my name is" + somename.name + " and I work in "+somename.companys".") obj = GFG("John", “VIT") Hello my name is John and | work in VIT. obj show() In this example, we are creating a GFG class and we have created the name, and company instance variables in the constructor. We have created a method named say_hil) which returns the string “Hello my name is” + {name} +" and | work in “H{company}+”.”We have created a person class object and we passing the name John and Company VIT to the instance variable. Finally, we are calling the show() of the class. Following table lists some generic functionality that you can override in your own classes — Sr.No. Method, Description & Sample Call __ (self Largs...]) 1 Constructor (with any optional arguments) Sample Call : obj = className(args) —del__( self ) 2 Destructor, deletes an object Sample Call : del obj _repr__( self ) 3 Evaluable string representation Sample Call : repr(obj) _str__( self ) 4 Printable string representation ‘Sample Call : str(obj) —emp__( self, x) 5 Object comparison ‘Sample Call : cmp(obj, x) _init__() Function + To understand the meaning of classes we have to understand the built-in __init__() function. + All classes have a function called __init__(), which is always executed when the class is being initiated necessary to do when the object is being created Example Create a class named Person, use the to assign values for name and age: Use the __init__() function to assign values to object properties, or other operations that are init__() function Note: The __init_{() function is called automatically every time the class is being used to create a new object. class Person: def init__(self, name, age): self.name = name self.age - age pl = Person(“John", 36) print(p1.name) nt(pl.age) John 36 __str_() Function + The _str__() function controls what should be returned when the class object is represented as a string + If the _str__() function is not set, the string representation of the object is returned: Example 1 The string representation of an object WITHOUT the __str__() function: class Person: def _init_(self, name, age): self.name = name self.age - age pl = Person(“John", 36) print(p1) <__main__.Person object at 0x15039e602100> Example 2 The string representation of an object WITH the __str__() function: [class Person def init__(self, name, age): self.nane = name self.age = age def __str_(self): return #"{self.name)({self.age})"| lpt = Person("John", 36) printpt) John(36) Object Methods Objects can also contain methods. Methods in objects are functions that belong to the object, Let us create a method in the Person class: Example Insert a function that prints a greeting, and execute it on the p1 object: class Person: def init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is * + self.name) pl = Person("John", 36) pi. myfunc Hello my name is John Modify Object Properties You can modify properties on objects like this: Set the age of p1 to 40: Pl.age = 40 Delete Object Properties You can delete properties on objects by using the del keywor Delete the age property from the p1 object: del_pl.age Delete Objects You can delete objects by using the del keyword: Delete the p1 object: del pl The pass Statement class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error. class Person: pass Problem 1: Create a Python class called Book that has the following features: * Four private instance variables: title, author, pages, and price. + Aconstructor that initializes these instance variables. + Amethod called get_info() that returns a string containing the book's title, author, and number of pages. + Amethod called apply_discount() that takes a discount percentage as an argument and applies it to the book's price. + Amethod called display() that prints the book's title, author, number of pages, and price. Create two instances of the Book class with different details and demonstrate the use of these methods. Code: Book _init_(self, title, author, pages, price) PS eee ta eestor Stee eed CS eed Steers get_info(self). Pee er) discount <= 100: self._price -= self._price * (discount / 100) atc ee) print aan ean ponas pared peace eee Dae seel een) Cosme SENT) pau print (book2..get_info()) Coro me eee) book2.display() Access Modifi rs Access modifiers are used by object oriented programming languages like C++, java, python etc. to restrict the access of the class member variable and methods from outside the class. Encapsulation is an OOPs principle which protects the internal data of the class using Access modifiers like Public, Private and Protected, Python supports three types of access modifiers which are public, private and protected. These access modifiers provide restrictions on the access of member variables and methods of the class from any object outside the class. ‘A Class in Python has three types of access modifiers: = Public Access Modifier = Protected Access Modifier = Private Access Modifier Public Access Modifier By default the member variables and methods are public which means they can be accessed from anywhere outside or inside the class. No public keyword is required to make the class or methods and properties public. Example The student class has two member variables, name and age and a method display which prints the member variable values. Both these variables and the methods are public as no specific keyword is assigned to them, Ge oS Name: John Age: 20 Private Access Modifier Class properties and methods with private access modifier can only be accessed within the class where they are defined and cannot be accessed outside the class. In Python private properties and methods are declared by adding a prefix with two underscores(‘_’) before their declar: Example The Class BankAccount is being declared with two private variables i.e account_number and balance and a private property display_balance which prints the balance of the bank account. As both the properties and method are private so while accessing them from outside the class it raises Attribute error. (steer ane rT Cua count_number = account_number Ere TEU ate ~ elf.__balance) ~ AttributeError: 'BankAccount' object has no attribute display_balance’ Protected Access Modifier Class properties and methods with protected access modifier can be accessed within the class and from the class that inherits the protected class. In python, protected members and methods are declared using single underscore( ('_’) as prefix before their names. Example ‘The Person class has two protected properties i.e _name and _age and a protected method _display that displays the values of the properties of the person class. The student class is inherited from Person class with an additional property i.e _roll_number which is also protected and a public method display that class the _display method of the parent class i.e Person class by creating an instance of the Student class we can call the display method from outside the class as the display method is private which calls the protected _display method of Person class. Ty ae Las ef _display(self) Tene print( Patra [ee She Cove super()-__init__( age) 11_number = roll_number Pear TENZ Crea) self._display() print(“Rol Sem oy Name: John Age: 20 rarer Roll Number: 123 Cre aEN 76} What is Data Modelling in Python? + The process of creating Data Models using the syntax and environment of the Python programming language is called Data Modelling in Python. + AData Model is a data abstraction model that organizes different elements of data and standardizes the way they relate to one another and to the properties of real-world entities. + Insimple words, Data Modelling in Python is the general process by which this programming language organizes everything internally and it treats and processes data. + The Data Model is the building block of Python. Internally Data Model has its design and code blocks for its implementation. + [tis composed of entities, and entities are none but the objects. It is said that everything is an object in Python. + Each entity has its own attributes (properties) and methods(actions) or behaviour associated with it. Each object has three attributes: an identity, a type, and a value. Identity of an object + Every object, either for Data Modelling in Python or any other activity involving Python's environment, has an identity which can never change once itis created. Think of identity as an object’s address in the memory + id{) is the function that gives us the identity of the object or we can say it returns the virtual memory address of the object. The memory address will be an integer value. >>> a="hevodata’ Python Code: >>> id(a) 1397871458544 >>> belo1 >>> id(b) 1623965024 >>> c="hevodata’ >>> id(c) 1397871458544 From the previous code of Data Modelling in Python, we can see variables ‘a’ and ‘b’ have different memory addresses but ‘a’ and ‘c’ have the same memory address as they have the same value We can check if two objects are identified using the ‘is’ operator. The ‘is’ operator basically compares the identity of two objects. If the identity of two variables is the same then it returns ‘True’ otherwise ‘False’. PythonCode: | >>> a is b False >> aisc True From the above code and output, itis clear that variables ‘a’ and ‘c’ have the same identity while ‘b’ has a different This is how the identity of an object is decided during Data Modelling in Python. identity than ‘a’ and ‘ Type of an Object During Data Modelling in Python, the type of an object means the name of the class to which the object belongs. Function type() tells the type of the object. By knowing the type of an object, it is easy for user's to specify two things. = The operation allowed on that object "The set of values the object can hold. The type of an object cannot change but under certain controlled conditions, it is possible to change the type of an object. Although it is not a good idea and not advisable as well >>> a= hevodata™ >>> xetype(a) >>> print ("Type of variable 'a' is: ", x) is: Type of variable >>> b=1e1 >>> y= type(b) >>> print("Type of variable ‘b' is Type of variable oy) is: >>> fruits = (‘apple', ‘banana’, ‘grapes’, ‘orange’} >>> t = type(fruits) >>> print("Type of variable ‘fruits’ is: ", t) Type of variable ‘fruits’ is: From the above python code and its output, you can see types of the different objects as different classes like ‘str’, ‘int, and ‘tuple’. Value of an Object ‘An object's value during Data Modelling in Python is the data that is stored for that object. The value object can hold is decided on the basis of the type of object. >>> vars'article' Python Code: >>> print("Value of variable ‘var’ is: ", var) Value of variable ‘var' is: article In the above code, ‘var" is the variable and ‘article’ is the value of ‘var’. ‘Object values are changeable and it depends on their type. Python supports the following 2 types of objects based on their values: = Mutable Objects = Immutable Objects There is some type for which the value of an object cannot change those are called immutable objects and whose value can be changed are called mutable objects. 1) Mutable Objects ‘The mutability of objects is decided on the basis of their type. whose values can be changed are called Mutable objects. s, Dictionaries are mutable objects. Those objects The following Python code is useful for creating a list for Data Modelling in Python: #let’s create a list >>> a= [11, 22, 33] >>> print("List values: a) >>> print("Identity of a: ",id(a)) List values: [11, 22, 33] Identity of a: 1397871407048 >>> a[@] >>> print("Changed List values: “,a) >>> print("Identity of a: ",id(a)) Changed List values: [1, 22, 33] Identity of a: 1307871407048 1 #Change first value of list 2) Immutable Objects During Data Modelling in Python, Immutable Objects are the objects that stored data but their values cannot be modified. Numbers, Strings, Tuples, and Sets are immutable. The following Python code is useful for creating a variable with string value during Data Modelling in Python let's create a varible with string value s = "Hevo! print("Variable value: ",s) print("Identity of s: ",id(s)) Variable value: Hevo Identity of s: 1397871732528 5 = "Data" #Change value of varibale print(*variable value: ",s) ",4¢(s)) print(*identity of s Variable value: bata Identity of s: 1397836021296 Special Methods for Data Modelling in Python Below are some of the examples of special methods for Data Modelling in Python which help to understand how these built-ins work in Python. + The __init__() method is for initialization and is called by the python interpreter itself when an instance of an object is created. + The len(x) method is for the length calculation of an object, internally the python interpreter calls x._len() + Call x{2] to get an item at location 2, internally the python interpreter calls x.__getitem__(2) * When str(x) is called, internally the python interpreter, calls x._str__() + Operators are also magic methods, add operator x + y actually turns to x.__add__(y) Data persistence + The word ‘persistence’ means "the continuance of an effect after its cause is removed". ‘The term data persistence means it continues to exist even after the application has ended. Thus, data stored in a non-volatile storage medium such as, a disk file is a persistent data storage. + Data persistence is the concept of storing data in a persistent form. It means that the data should be permanently stored on disk for further manipulation There are two types of system used for data persistence in common + File + Database File is an object allows to create 2 file and to manipulate its contain. + Files is an object in computer that stores data, information, settings or commands permanently. * Each files has a File_name. All information stored in a computer must be in the form of file. + There are different types of files, like data files, text files, program files etc. Relative and Absolute Path For example, if any file is located in D:/Pranshu/python/File.py Where, D :/Pranshu/python/File.py is absolute path and /python/File.py is the relative path. Pythor’s built in library contains various modules for serialization and deserialization process. Sr.No. Name & Description pickle Python specific serialization library marshal Library used internally for serialization shelve Pythonic object persistence dbm library offering interface to Unix database csv library for storage and retrieval of Python data to CSV format json Library for serialization to universal JSON format Pickle Module + The process to convert any kind of python objects (list, dict, tuple etc.) into byte streams (0s and 1s) is called as pickling or serialization or flattening or marshalling. + Itcan convert the byte stream (generated through pickling) back into python objects by a process called as unpickling or de-serialization. + In real world scenario, the use pickling and unpickling were widespread as they allow us to easily transfer data from one server/system to another and then store it ina file or database. + Python's terminology for serialization and deserialization is pickling and unpickling respectively. The pickle module in Python library, uses very Python specific data format. Hence, non-Python applications may not be able to deserialize pickled data properly, It is also advised not to unpickle data from un-authenticated source. Pickling module is used for serialization and deserialization python object. pickle.dump () method is used to pickle object pickel.load () method is used to un-pickle objects Example import pickle a= [/Python’, 10, ‘Programming’] b= open(‘D:/file.txt,wb') pickle.dump(a,b) import pickle file=opentD:/file.txt' rb’) print (pickle.load{{ile)) 4 [‘Python’, 10, ‘Prograrnming') Marshal Module Object serialization features of marshal module in Python's standard library are similar to pickle module. However, this module is not used for general purpose data. On the other hand, it is used by Python itself for Python's internal object serialization to support read/write operations on compiled versions of Python module: import marshal a= [’Python’, 10, ‘Programming’) b= opent’D:/file.txt'wb') marshal.dump(a,b) import marshal file=open(‘D:/file.txt! rb’) print (marshal.load(file)) [’Python', 10, ‘Programming') Persistence storage Module (Shelve Module) + The shelve module in Python's standard library isa simple yet effective tool for persistent data storage when using a relational database solution is not required *+ Only string data type can be used as key in this special dictionary object, whereas any picklable object can serve as value. The shelve module defines three classes as follows ~ Sr.No. Module & Description Shelf This is the base class for shelf implementations. It is initialized with dict-like object. BsdDbShelf This Is 2 subclass of Shelf class. The dict object passed to its constructor must support first(), next(), previous(), last() and set_location() methods. DbfilenameShelf This Is also a subclass of Shelf but accepts a filename as parameter to its constructor rather than dict object. Following code creates a database and stores dictionary entries in it. import shelve s = shelve.open("test") s[‘name’] = "ajay" s[‘age’] = 23 s[‘marks*] = 75 close() This will create test.dir file in current directory and store key-value data in hashed form. The Shelf object has following methods available ~ Sr.No. Method & Description dose) synchronise and close persistent dict object. 2 syne) Write back all entris inthe cache if shelf was opened with writeback set to True 3 set returns value associated with key 4 ttems() lot of tuples - each tuple is key value pair keys) s list of shelf keys 5 POR) remove specifiad key and return the corresponding valve 7 update() Update shelf from another dictiterable values ° 0 list of shelf values To access value of a particular key in shelf. >>> s=shelve.open(‘test') >>> s['age'] 23 >>> s['age']=25 >>> s.get(‘age') 25 1 items(), keys() and values() methods return view objects >>> list(s.items()) [(name', 'Ajay'), ('age’, 25), (‘marks', 75)] >>> list(s.keys()) [name', ‘age’, 'marks"] >>> list(s.values()) ['Ajay’, 25, 75] ‘To remove a key-value pair from shelf >>> s.pop('marks') 75 >>> list(s.items()) [Cname’, ‘Ajay'), (‘age', 25)] Notice that key-value pair of marks-75 has been removed. ‘To merge items of another dictionary with shelf use update() method >>> d={'salary':10000, ‘designation':'manager'} >>> s.update(d) >>> list(s.items()) [Cname’, 'Ajay’), (‘age’, 25), (‘salary', 10000), (‘designation’, ‘manager') dbm package + The dom package presents a dictionary like interface DBM style databases. DBM stands for DataBase Manager. This is used by UNIX (and UNIX like) operating system. + The database stores data by use of a single key (a primary key) in fixed-size buckets and enables fast retrieval of the data by key. Example: Import dbm f-dbm.open("D:/data.db",’n") f{‘name"] = “Python” f’age”]=25 fi"'marks”] = 75 fclose() The open() function allows mode these flags Sr.No. Value & Meaning + open existing database for reading only (default) > ow Open existing database for reading and writing ; Open database for reading and writing, creating It if it doesn’t exist oa 4 Always create a new, empty database, open for reading and writing The dbm object is a dictionary lke object, just as shelf object. Hence, all dictionary operations can be performed. The dbm object can invoke get(), pop(), append() and update() methods. Following code opens ‘mydbm.db' with 'r' flag and iterates over collection of key-value pairs. Instance method A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifyiny fz Python program to demonstrate li classes lelass person: # init method or constructor def _init_(self, nane) clf.nane = name # sample method def say_hi(self) print("Hello, my name is", se lp = Person(*Nikhil”) lp-say hi() name) its state. Hello, my name is Nikhil fe Bython progran To dononstrate Js instance wathods Jelass. shape: # calling Constructor def _init_(self, edge, color): velfvedge = edge elf.colar = color anstance Hethos def FinEdges (sel): return self edge # Instance Wethad def nodifyedges(sclF, nevedge) elf edge = newedge J oriver code Jcircle = shape(o, ‘red") square = shape(#, ‘blue") + calling instance method print("no. of edges for circle: “+ ste(cinele.Finedges()) Jt calling instance method square.modi FyEdges (6) print(io. of edges for square: “+ ste(square.Finedges()) For example, consider a class shapes that have many objects like circle, square, triangle, etc. having its own attributes and methods. An instance attribute refers to the properties of that particular object like edge of the triangle being 3, while the edge of the square can be 4. L Wo. of edges for circle: No. of edges for square: Try Except/ Block The try block lets you test a block of code for errors. ‘The except block lets you handle the error. ‘The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks. Exception Handling When an error occurs, or exception as we call it, Python will normally stop and generate an error message. ‘These exceptions can be handled using the try statement: The try block will generate an exception, because x is not defined tr ex! print(x) cept print(“An exception occurred” ‘An exception occurred Since the try block raises an error, the except block will be executed. Without the try block, the program will crash and raise an error: Example This statement will raise an error, because x is not defined: print(x) Traceback (most recent call last): File "demo_try_except_error.py”, line 1, in print(x) NameError: name 'x' is not defined Many Exceptions You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error: Example Print one message if the try block raises a NameError and another for other errors: try: print(x) except NameErrar: print("Variable x is not defined") except print("“Something else went wrong") Variable xis not defined The try block will generate a NameError, because x is not defined Else You can use the else keyword to define a block of code to be executed if no errors were raised: Example In this example, the try block does not generate any error: try: print("Hello”) except: print("Something went wrong”) else: Hello print("Nothing went wrong”) Nothing went wrong The try block does not raise any errors, so the else block is executed: Finally The finally block, if specified, will be executed regardless if the try block raises an error or not. Example try print (x) except: print ("Something went wrong”) finally: Something went wrong, The ‘try except is finished print("The ‘try except’ is finished")| The finally block gets executed no matter if the try block raises any errors or not: What is Inheritance in Python? + Inheritance is one of the most important features of object-oriented programming languages like Python. It is used to inherit the properties and behaviours of one class to another. The class that inherits another class is called a child class and the class that gets inherited is called a base class or parent class. + Ifyou have to design a new class whose most of the attributes are already well defined in an existing class, then why redefine them? Inheritance allows capabilities of existing class to be reused and if required extended to design a new class. + Inheritance comes into picture when a new class possesses 'IS A’ relationship with an existing class. For example, Car IS.a vehicle, Bus IS a vehicle, Bike IS also a vehicle. Here, Vehicle is the parent class, whereas car, bus and bike are the child classes. Types of Inheritance In Python, inheritance can be + Single Inheritance + Multiple Inheritance * Multilevel Inheritance + Hierarchical Inheritance + Hybrid Inheritance Single inheritance Single Inheritance: This is the simplest form of inheritance where a child class inherits attributes and methods from only one parent class, Multiple inheritance: Multiple inheritance in Python allows you to construct a class based on more than one parent classes, The Child class thus inherits the attributes and method from all parents. The child can override methods inherited from any parent. Multilevel inheritance: In multilevel inheritance, a class is derived from another derived class. There exists multiple layers of inheritance. We can imagine it as a grandparent-parent-child relationship. Hierarchical Inheritance: This type of inheritance contains multiple derived classes that are inherited froma single base class. This is similar to the hierarchy within an organization Hybrid Inheritanc ‘ombination of two or more types of inheritance is called as Hybrid Inheritance. For instance, it could be a mix of single and multiple inheritance, Python Inheritance + Inheritance allows us to define a class that inherits all the methods and properties from another class. + Parent class is the class being inherited from, also called base class. + Child class is the class that inherits from another class, also called derived class. Create a Parent Class Any class can be a parent class, so the syntax is the same as creating any other class Example Create a class named Person, with Firstname and lastname properties, and a printname method: John Doe class Person! def _ self. firstname = fame nit_(self, Frame, Iname) self-lastnane = Inane def printnama(self): print(self.firstname, self. Lastname) Use the Person class to create an object, and then execute the printnane method: x = Person("John", "Doe") printnan Create a Child Class To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class: Example Create a class named Student, which will inherit the properties and methods from the Person cla: class Student (Person): pass Now the Student class has the same properties and methods as the Person class. Example Use the Student class to create an object, and then execute the printname method: x = Student("Mike", "Olsen")| x. printname( “\ imine olsen ‘Add the _i t_() Function So far we have created a child class that inherits the properties and methods from its parent. + We want to add the __init__() function to the child class (instead of the pass keyword). Note: The __init__() function is called automatically every time the class is being used to create a new object. Example Add the t_() function to the Student class: class Student (Person) def init__(self, fname, Iname) 4 Hadd operties etc When you add the _i t_() function, the child class will no longer inherit the parent's __init__() function, Note: The child's __i t_() function overrides the inheritance of the parent's _init__() function. ‘To keep the inheritance of the parent's __init__() function, add a call to the parent's it__() function: Example class Student (Person): def init__(self, fname, Iname): Person. init__(self, fname, Iname) Mike Olsen Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in the __init__() function. Use the super() Function Python also has a super() function that will make the child class inherit all the methods and properties from its parent: Example [class Student (Person def __init_(self, fname, Iname) super().__init__(fname, Iname) Mike Olsen By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its pare Add Properties Example Add a property called graduationyear to the Student class: class Student(Person): def __init_(self, fname, Iname): super().__init__(fname, name) 2019 self. graduationyear = 2019 In the example, the year 2019 should be a variable, and passed into the Student class when creating student objects. To do so, add another parameter in the __init__() function: Example ‘Add a year parameter, and pass the correct year when creating objects: class Student(Person): def init__(self, fname, Iname, year): super().__init__(fname, Iname) self.graduationyear = year 2019 X = Student("Mike", "Olsen", 2019) ‘Add Methods ‘Add a method called welcome to the Student class: Welcome Mike Olsen to the class of 2019 [class Student (Person): def _init_(self, fname, Iname, year): super().__init__(fname, Iname) self.graduationyear = year def welcome(self) print("Nelcone", self.firstname, self.lastname, "to the class of", self.graduationyear)| If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridder Exception Handling Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events ‘occur which change the normal flow of the program ifferent types of exceptions in python: In Python, there are several built-in Python exceptions that can be raised when an error occurs during the execution of a program. Here are some of the most common types of exceptions in Python: ‘+ Syntaxérror: This exception is raised when the interpreter encounters a syntax error in the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis, + TypeError: his exception is raised when an operation or function is applied to an object of the wrong type + NameError: This exception is raised when a variable or function name is not found in the current scope. + Index€rror: This exception is raised when an index is out of range fora list, tuple, or other sequence types. + KeyError: This exception is raised when a key is not found in a dictionary. + ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero. Difference between Syntax Error and Exceptions Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the termination of the program. Exampl ‘There is a syntax error in the code . The ‘if statement should be followed by a colon (:), and the ‘print’ staternent should be indented to be inside the ‘if’ block. fanount = 10000 |if(amount > 2999) print("You are eligible to purchase psa self paced") File *Thone/acs5380186 TaTROSSTTAGEOTIIOD py, Tine 4 Isyntaxerros Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program. Example: Here in this code as we are dividing the ‘marks’ by zero so a error will occur known as ‘ZeroDivisionError’ marks = 10000 a= marks / 0 print(a) Fle “/none/#3ee0stzeabssio¥bat0sr208220207.09", Line 4 In the above example raised the ZeroDivisionError as we are trying to divide a number by 0. Note: Exception is the base class for all the exceptions in Python. You can check the exception hierarchy Exampl 1) TypeError: This exception is raised when an operation or function is applied to an object of the wrong type. Here's an example: Here a ‘Typerror’ is raised as both the datatypes are different which are being added, pe = Traceback (nost recent coll Test) ly = “hello” File “7adfuds0-oa3e-4a44-08F2-S544N60bF6te.py", Lina 4, Sn cnodule Zexty ney Typescror: uneupportee operand type(s) for 4s ‘int! ang ‘ete try catch block to resolve The code attempts to add an integer (‘x’) and a string ('y') together, which is not a valid operation, and it will raise a ‘TypeError’. The code used a ‘try’ and ‘except' block to catch this exception and print an error message, key Jexcept Typetrror: 7 print("error: cannot add an int and a str) | [Errors cannot add an int and a str ‘Try and Except Statement ~ Catching Exceptions ‘Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause. Example: Here we are trying to access the array element whose index is out of bound and handle the corresponding exception. a= (1, 2, 3] try: print ("Second element = %d" %(a[1])) print ("Fourth element xa" %(a[3])) excep} Second element print ("An error occurred") Anenronoccunred In the above example, the statements that can cause the error are placed inside the try statement (second print statement in our case). The second print statement tries to access the fourth element of the list which is not there and this throws an exception, This exception is then caught by the except statement. try: # statement(s) except IndexError: # statement(s) except VelueError: Catching Specific Exception Atry statement can have more than one except clause, to specify handlers for different exceptions. Please note that at most one handler will be executed. For example, we can add IndexError in the above code. The general syntax for adding specific exceptions are — # statement(s) The code defines a function ‘fun(a)' that calculates b based on the input a. Ifa is less than 4, it attempts a division by zero, causing a ‘ZeroDivisionError’. The code calls fun(3) and fun(5) inside a try-except block. It handles the ZeroDivisionError for fun(3) and prints “ZeroDivisionError Occurred and Handled.” The ‘Name€rror' block is not executed since there are no ‘NameError' exceptions in the code. fat Foncay act b= ayaa) prant(value of b=", b) Zerebivistonérror Occurred and Handled funca) funts) Ifyou comment onthe line fun3), the output wil be colvislontecar occurred and Handled") int (Mancerror Occurred and Handed") aneError Occurred and tangles Try with Else Clause In Python, you can also use the else clause on the try-except block which must be present after all the except clauses, The code enters the else block only if the try clause does not raise an exception, ‘The code defines a function AbyB(a, b) that calculates c as ((a+b) / (a-b)) and handles a potential Zerot sionError. It prints the result if there's no division by zero error. Calling AbyB(2.0, 3.0) calculates and prints -5.0, while calling AbyB(3.0, 3.0) attempts to divide by zero, resulting in a ZeroDI isionError, which is caught and “a/b results in 0” is printed. def Abye(a, b) try: = ((ab) / (a-b)) except ZeroDivisionError: print ("a/b result in 0") else: orint (c) -5.8 labya(2.0, 3.0) : AiataTes 3.8) a/b result in @ Finally Keyword in Python ma Python provides a keyword finally, which is always executed | **°*?* ope onal block after the try and except blocks. The final block always # warding executes after the normal termination of the try block or eg after the try block terminates due to some exception sreaption (4f required) # execute Lf no exception finally Example: # Sone code --.. (always executed) The code attempts to perform integer division by zero, resulting in a ZeroDivisionError. It catches the exception and prints “Can't divide by zero.” Regardless of the exception, the finally block is executed and prints “This is always executed.” Rey: k= slo neck) prane(*can't divide by zero") Can't divide by zero fsnatay: int¢"Ths 1s always executed’ This is always executed Raising Exception The raise statement allows the programmer to force a specific exception to occur. The sole argument in raise indicates the exception to be raised, This must be either an exception instance or an exception class (a class that derives from Exception). fey: raise Nameerror( lexcept Nameerror: print (“an exception") raise ii there” Traceback (most recent call last): File "/home/déect4casssb97bFfedses4bbf212a9f. py", line 5, in raise Nameérror("Hi there") # Raise Error NaneError: Hi there ‘The output of the above code will simply line printed as “An exception” but a Runtime error will also occur in the last due to the raise statement in the last line Advantages of Exception Handling: + Improved program reliability: By handling exceptions properly, you can prevent your program from crashing or producing incorrect results due to unexpected errors or input. + Simplified error handling: Exception handling allows you to separate error handling code from the main program logic, making it easier to read and maintain your code. + Cleaner code: With exception handling, you can avoid using complex conditional statements to check for errors, leading to cleaner and more readable code. + Easier debugging: When an exception is raised, the Python interpreter prints a traceback that shows the exact location where the exception occurred, making it easier to debug your code. Disadvantages of Exception Handling: Performance overhead: Exception handling can be slower than using conditional statements to check for errors, as the interpreter has to perform additional work to catch and handle the exception. Increased code complexity: Exception handling can make your code more complex, especially if you have to handle multiple types of exceptions or implement complex error handling logic. Possible securit improperly handled exceptions can potentially reveal sensitive information or create security vulnerabilities in your code, so it’s important to handle exceptions carefully and avoid exposing too much information about your program. Polymorphism The word “polymorphism” means "many forms", and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or classes. Function Polymorphism ‘An example of a Python function that can be used on different objects is the len() function, String For strings len() returns the number of characters: lello World! print(Len(x)) Fy Tuple For tuples len() returns the number of items in the tuple: inytuple = ("apple", “banana”, “cherry") print (1en(mytuple)) 3 Dictionary For dictionaries len() returns the number of key/value pairs in the dictionary: print(len(thisdict)) 3 lass Polymorphism Polymorphism is often used in Class methods, where we can have multiple classes with the same method name. | prive! For example, say we have three classes: Car, Boat, and Plane, and they all have a method called move(): sail! [class Car: ese aes Fly! def _init_(self, brand, model): def init__(self, brand, model): T self.brand = brand self.model = model self.brand = brand self.model = model def move(self): ndamnitorivel”) def move(self): print("Fly!") class Boat: def init__(self, brand, model): carl = Car("Ford”, “Mustany ) sel¥.brand = brand boati = Boat("Ibiza", “Touring 20") self.model = model planet = Plane("Boeing", "747") def move(sel#): for x in (cart, boat1, plane): print("saill”) x.move() Inheritance Class Polymorphism Create a class called Vehicle and make Car, Boat, Plane child classes of Vehicle: class Vehicle: def _init_(self, brand, model); self.brand = brand self model model def move(self): print ("Hove class Car(Vehicle): pass class Boat(Vehicle): def move(self): print("Saill") Ford Mustang Move! Ibiza Touring 20 sail! Boeing 747 Fly! [class Plane (Vehicle): def move(self): print("Fly!") cart = Car(“Ford", "Mustang") #Create a Car object looata = Boat( “Touring 20") #Create a Boat object] Jplanel = Plane("Boeing", "747") #Create a Plane object biza” |for x in (card, boati, planet): print (x.brand) print(x.model) move() What is Polymorphism in Python? The term polymorphism refers to a function or method taking different forms in different contexts. Since Python is a dynamically typed language, polymorphism in Python is very easily implemented. Ifa method in a parent class is overridden with different business logic in its different child classes, the base class method is a polymorphic method. Ways of implementing Polymorphism in Python Polymorphism There are four ways to implement polymorphism in Python ~ + Duck Typing + Operator Overloading ‘+ Method Overriding + Method Overloading Duck Typing in Python: Duck typing is a concept where the type or class of an object is less important than the methods it defines, Using this concept, you can call any method on an object without checking its type, as long as the method exists. This term is defined by a very famous quote that states: Suppose there is a bird that walks like a duck, swims like a duck, looks like a duck, and quaks like a duck then it probably is a duck. Operator overloading: It allows you to redefine the behavior of built-in operators for user-defined classes. This means you can define how operators like +, -, *, /, etc., behave when applied to objects of your class. This is achieved by defining special methods, also known as magic methods, in your class. Method Overriding in Python: In method overriding, a method defined inside a subclass has the same name as a method in its superclass but implements a different functionality. Method Overloading in Python: When a class contains two or more methods with the same name but different number of parameters then this scenario can be termed as method overloading. Python does not allow overloading of methods by default, however, we can use the techniques like variable-length argument lists, multiple dispatch and default parameters to achieve this. Operator Overloading Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because ‘#” operator is overloaded by int class and str class print (14 + 32) # Now, we will concatenate the two strings print (“Python" + “Programming") # We will check the product of two numbers print (23 * 14) 46 PythonProgramming # Here, we will try to repeat the String 322 print ("XY 2" * 3) XYZXYZXYZ You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading. How to Overload the Operators in Python? ‘Suppose the user has two objects which are the physical representation of a user-defined data type class. The user has to add two objects using the "+" operator, and it gives an error. This is because the compiler does not know how to add two objects. So, the user has to define the function for using the operator, and that process is known as “operator overloading’. The user can overload all the existing operators by they cannot create any new operator. Python provides ‘some special functions, or we can say magic functions for performing operator overloading, which is automatically invoked when it is associated with that operator. Such as, when the user uses the "+" operator, the magic function __add__will automatically invoke in the command where the "+" operator will be defined. How to Perform Binary "+" Operator in Python: ‘When the user uses the operator on the user-defined data types of class, then a magic function that is associated with ‘the operator will be invoked automatically. The process of changing the behaviour of the operator is as simple as the behaviour of the function or method defined. ‘The user define methods or functions in the class and the operator works according to that behaviour defined in the functions. When the user uses the "+" operator, it will change the code of a magic function, and the user has an extra meaning of the "+" operator. Program 1: Simply adding two objects. Python program for simply using the overloading operator for adding two objects. class example: det _init_(self, x: seliX = x # adding two objects def _add_(celf, U): return selfX + UX object_1 = example( int( input{ print ("Please enter the value: ")) object 2 = example int( input{ print (‘Please enter the value: "))) print (*:", object_1 + object 2) object_3 = example(str( input{ print (“Please enter the value: “))) object 4 = example(str( input{ print ("Please enter the value: “)) print (°:", object_3 + object_4) Please enter the value: 23 Please enter the value: 21, 44 Please enter the value: Python Please enter the value: Programming : PythonProgramming Program 2: defining Overloading operator in another object, Python program for defining the overloading operator inside another object. ‘lass complex1 def _init_(self x, Y): selfX =X selfY =¥ # Now, we will add the two objects det _add_(self, Uy return selfX + UX, selfY ~ UY Object_1 = complex_1(23, 12) Object_2 = complex 1(21, 22) Object_3 = Object_1 + Object 2 print (Object 3) (44, 34) Program 3: Overloading comparison operators in Python Python program for overloading comparison operators. lass example def init_(self, sellX =X def _gt_(sel, Us iffselx > UX: return True bse: return False ut object 2 example_i(int{ input print (Please enter the val Ifobject_1 > object 2): print (‘The object_t is greater than object else print (‘The object.2 is greater than object_1) example (int (input print( Please enter the value: ")) Case 1: Please enter the value: 23 Please enter the value: 12 ‘The object_1 is greater than object_2 Case 2: Please enter the value: 20 Please enter the value: 31 The object_2 is greater than object_1 Abstract Classes in Python ‘An abstract class can be considered a blueprint for other classes. It allows you to create a set of methods that must be created within any child classes built from the abstract class. A class that contains one or more abstract methods is called an abstract class. An abstract method is a method that has a declaration but does not have an implementation. We use an abstract class while we are designing large functional units or when we want to provide a common interface for different implementations of a component. Abstract Base Classes in Python By defining an abstract base class, you can define a common Application Program Interface(APl) for a set of subclasses. This capability is especially useful in situations where a third party is going to provide implementations, such as with plugins, but can also help you when working in a large team or with a large code base where keeping all classes in your mind is difficult or not possible. Working on Python Abstract classes By default, Python does not provide abstract classes. Python comes with a module that provides the base for defining ‘Abstract Base classes(ABC) and that module name is ABC, ‘ABC works by decorating methods of the base class as an abstract and then registering concrete classes as implementations of the abstract base. A method becomes abstract when decorated with the keyword @abstractmethod. Example 1: + This code defines an abstract base class called “Polygon” using the ABC (Abstract Base Class) module in Python. The “Polygon” class has an abstract method called “noofsides” that needs to be implemented by its subclasses. + There are four subclasses of “Polygon” defined: “Triangle,” “Pentagon,” “Hexagon,” and “Quadrilateral.” Each of these subclasses overrides the “noofsides” method and provides its own implementation by printing the number of sides it has. + Inthe driver code, instances of each subclass are created, and the “noofsides” method is called on each instance to display the number of sides specific to that shape, [F Python program showing lt abstract base class work lfrom abe import asc, abstractmethod lclass Polygon(aac): @abstractmethod def noofsides(self): pass lclass Triangle(Polygon): # overriding abstract method def noofsides(self): print("I have 3 sides") lclass Pentagon(Polygon): # overriding abstract method def noofsides(self): print("r have 5 sides") ‘lass Hexagon(Polygon): # overriding abstract method def noofsides(self): print("I have 6 sides") class Quadrilateral (Polygon) # overriding abstract method def noofsides(self): print("I have 4 sides") # Driver code R = Triangle() R.noofsides() K = quadrilateral() K.noofsides() R = Pentagon() R.noofsides() K = Hexagon() K.noofsides() Ihave 3 sides Ihave 4 sides Ihave 5 sides Ihave 6 sides Example 2: Here, This code defines an abstract base class called “Animal” using the ABC (Abstract Base Class) module in Python. The “Animal” class has a non-abstract method called “move” that does not have any implementation. There are four subclasses of “Animat" defined: “Human,” “Snake,” “Dog,” and “Lion.” Each of these subclasses overrides the “move” method and provides its own implementation by printing a specific movement characteristic. % Python program showing lass Dog(aninaly # abstract base class work from abe import alc, abstractmathod def nove(self): print("T can bark") class Animal (AC): eae a def nove(self) def move(self) print("I can roar") pass lass Hunan (Aninal) Lean def nove(self) . = snake() print("r can walk and runt) | | aoetes lass Snake(aninal): 8 = og) year walk and run eu can craw det nove(self) ; | can bark print("E can crawl") Eee I can roar Probler Write the Python Program to design a simple system to manage animals in a zoo. Create a base class Animal that has the following properties and methods: Proper + name: the name of the animal + age: the age of the animal. Methods: + speakl): This method should be defined in the derived classes to make a sound specific to the animal. + info(): This method should print the name and age of the animal. Create derived classes Dog, Cat, and Bird that inherit from Animal. Each derived class should override the speakl) method to print a sound specific to the animal (e.g., "Woof" for dogs, "Meow' for cats, "Tweet" for birds) Demonstrate polymorphism by writing a function that takes a list of animals and calls the speak() and info() methods on each animal. (self, name, age) eens sel on esreyey) (self) penne EC TESICxe) animal .speak() Eee a Paar ar) Dette ESCs Coca] Poe ee ero) Thank you!!

You might also like