Object oriented Programming
Class and Objects A class is a blueprint from which individual objects are created. An object is a bundle of related state (variables) and behavior (methods). Objects contain variables, which represents the state of information about the thing you are trying to model, and the methods represent the behavior or functionality that you want it to have
continued Variables refers to both Instance variables and Class variables, unless explicitly specified. Class objects are often used to model the real-world objects that you find in everyday life. Objects are key to understanding object- oriented technology. Look around right now and you’ll find many examples of real-world objects: your dog, your desk, your television set, your bicycle. Real- world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming
Creating Classes in Python Related variables and methods are grouped together in classes. The simplest form of class definition looks like this: class ClassName: <statement1> ------- <statement>
continued Classes are defined by using the class keyword, followed by the ClassName and a colon. Class definitions must be executed before they have any effect. In practice, the statements inside a class definition will usually be function definitions, but few other statements are allowed. Because these functions are indented under a class, they are called methods. Methods are a special kind of function that is defined within a class. Python program to illustrate classes and object creation Filename:c1.py,c2.py
Class mobile Let’s define a class called Mobile that has two methods associated with it one is receive_message() and another is send_message(). The first parameter in each of these methods is the word self. Self is a default variable which contains the memory address of the invoking object of the class. In the method definition, self doesn’t need to be the only parameter and it can have multiple parameters. Creating the Mobile class provided us with a blueprint for an object. Just because you have defined a class doesn’t mean you have created any Mobile objects. __init__ (self) is a special method called as constructor. It is implicitly called when object of the class is created
Creating Objects in Python Object refers to a particular instance of a class where the object contains variables and methods defined in the class. Class objects support two kinds of operations: attribute references and instantiation. The act of creating an object from a class is called instantiation. The names in a class are referenced by objects and are called attribute references. There are two kinds of attribute references, data attributes and method attributes. Variables defined within the methods are called instance variables and are used to store data values. New instance variables are associated with each of the objects that are created for a class. These instance variables are also called data attributes. Method attributes are methods inside a class and are referenced by objects of a class. Attribute references use the standard dot notation syntax as supported in Python. • object_name.data_attribute_name • object_name.method_attribute_name() . The syntax for Class instantiation is, • object_name = ClassName(argument_1, argument_2, ….., argument_n) optional
The Constructor Method Python uses a special method called a constructor method. Python allows you to define only one constructor per class. Also known as the __init__() method, it will be the first method definition of a class and its syntax is,
continued The __init__() method defines and initializes the instance variables. It is invoked as soon as an object of a class is instantiated. The __init__() method for a newly created object is automatically executed with all of its parameters. The __init__() method is indeed a special method as other methods do not receive this treatment. The parameters for __init__() method are initialized with the arguments that you had passed during instantiation of the class object. Class methods that begin with a double underscore (__) are called special methods as they have special meaning. The number of arguments during the instantiation of the class object should be equivalent to the number of parameters in __init__() method (excluding the self parameter).
Programs on classes Python program to create a class Mobile with attributes name, price and model. Use constructor to initialize the instance variable and display method to display the details of a mobile filename:c3.py Python program to create a class Student with attributes name, sem division and USN. Use to set() to initialize the attributes and get() method to display the details of a student Filename:c4.py Write Python Program to Calculate the Arc Length of an Angle by Assigning Values to the Radius and Angle Data Attributes of the class ArcLength Filename:c5.py
Access specifiers By default all members are public Variable name or method name prefixed with single underscore(_) are treated as protected member self._name=‘raj’ def _display(self): Variable name or method name prefixed with double underscore(__) are treated as private member self.__name=‘raj’ def __display(self):
continued Write Python Program to Simulate a Bank Account with private data attributes name and balance and protected methods depositMoney, withdrawMoney and showBalance filename:c6.py
Classes with Multiple Objects Multiple objects for a class can be created while attaching a unique copy of data attributes and methods of the class to each of these objects. Define a class student with private data attributes name and marks. Read n student details and print student details along with grade obtained. Filename c7.py Write a python program to simulate bank operations using class concept Filename:c8.py
Default parameters Python program to illustrate default parameters Filename:c9.py
Using Objects as Arguments An object can be passed to a calling function as an argument Python Program to Demonstrate Passing of an Object as an Argument to a Function Call filename:c10.py Given Three Points (x1, y1), (x2, y2) and (x3, y3), Write a Python Program to Check If they are Collinear using class concept Filename:c11.py Three points lie on the straight line if the area formed by the triangle of these three points is zero. So we will check if the area formed by the triangle is zero or not Formula for area of triangle is : 0.5 * [x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)]
Objects as Return Values It is important to note that everything in Python is an object, including classes. In Python, “everything is an object” (that is, all values are objects) because Python does not include any primitive, unboxed values. Anything that can be used as a value (int, str, float, functions, modules, etc.) is implemented as an object. The id() function is used to find the identity of the location of the object in memory. The syntax for id() function is id(object) This function returns the “identity” of an object. This is an integer (or long integer), which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
continued You can check whether an object is an instance of a given class or not by using the isinstance() function. The syntax for isinstance() function is, isinstance (object, classinfo) where the object is an object instance and classinfo can be a class, or a tuple containing classes, or other tuples. The isinstance() function returns a Boolean stating whether the object is an instance or subclass of another object.
program Given the Coordinates (x, y) of a Center of a Circle and Its Radius, Write Python Program to Determine Whether the Point Lies Inside the Circle, On the Circle or Outside the Circle using class Circle Filename:c12.py The idea is compute distance of point from center. If distance is less than or equal to radius. the point is inside, else outside. If((x-cir_x)*(x-cir_x)+(y-cir_y)*(y-cir_y)==r*r Write Python Program to Compute the End Time, While Start Time and Duration are Given using a class Time Filename:c13.py
Class Attributes versus Data Attributes Generally speaking, Data attributes are instance variables that are unique to each object of a class, and Class attributes are class variables that is shared by all objects of a class. Program to Illustrate Class Variables and Instance Variables Filename:c14.py
Encapsulation Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). Encapsulation is the process of combining variables that store data and methods that work on those variables into a single unit called class. In Encapsulation, the variables are not accessed directly. It is accessed through the methods present in the class. Encapsulation ensures that the object’s internal representation (its state and behavior) are hidden from the rest of the application. Thus, encapsulation makes the concept of data hiding possible. Given a point(x, y), Write Python Program to Find Whether it Lies in the First, Second, Third or Fourth Quadrant of x - y Plane filename:c15.py
Inheritance Inheritance enables new classes to receive or inherit variables and methods of existing classes. Inheritance is a way to express a relationship between classes. If you want to build a new class, which is already similar to one that already exists, then instead of creating a new class from scratch you can reference the existing class and indicate what is different by overriding some of its behavior or by adding some new functionality. A class that is used as the basis for inheritance is called a superclass or base class. A class that inherits from a base class is called a subclass or derived class. The terms parent class and child class are also acceptable terms to use respectively. A derived class inherits variables and methods from its base class while adding additional variables and methods of its own. Inheritance easily enables reusing of existing code.
Continued The relationship between derived classes and base class using the phrase is-a, then that relationship is inheritance. For example, a lemon is-a citrus fruit, which is-a fruit. A shepherd is-a dog, which is-a animal. A guitar is-a steel-stringed instrument, which is-a musical instrument. If the is-a relationship does not exist between a derived class and base class, you should not use inheritance.
The syntax for a derived class definition To create a derived class, you add a BaseClassName after theDerivedClassName within the parenthesis followed by a colon. The derived class is said to directly inherit from the listed base class.
continued In place of a base class name, other arbitrary expressions are also allowed. This can be useful, for example, when the base class is defined in another module:
program Program to Demonstrate Base and Derived Class Relationship Without Using __init__() Method in a Derived Class Filename:c16.py
Using super() Function and Overriding Base Class Methods In a single inheritance, the built-in super() function can be used to refer to base classes without naming them explicitly, thus making the code more maintainable. If you need to access the data attributes from the base class in addition to the data attributes being specified in the derived class’s __init__() method, then you must explicitly call the base class __init__() method using super() yourself, since that will not happen automatically. However, if you do not need any data attributes from the base class, then no need to use super() function to invoke base class __init__() method. The syntax for using super() in derived class __init__() method definition looks like this: super().__init__(base_class_parameter(s)) Its usage is shown below. class DerivedClassName(BaseClassName): def __init__(self, derived_class_parameter(s), base_class_parameter(s)) super().__init__(base_class_parameter(s)) self.derived_class_instance_variable = derived_class_parameter
program Program to Demonstrate the Use of super() Function filename:c17.py Define derived class Enggstudent from a base class Student with private attributes branch semester and division. Base class has private members name and USN. Override display method in base and derived class to display the details of a student Filename:c18.py
Multiple Inheritances Python also supports a form of multiple inheritances. A derived class definition with multiple base classes looks like this: class DerivedClassName(Base_1, Base_2, Base_3): <statement-1> . . . <statement-N> Derived class DerivedClassName is inherited from multiple base classes, Base_1, Base_2, Base_3. For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy. Thus, if an attribute is not found in DerivedClassName, it is searched for in Base_1, then (recursively) in the base classes of Base_1, and if it was not found there, it would be searched for in Base_2, and so on. Even though multiple inheritances are available in Python programming language, it is not highly encouraged to use it as it is hard and error prone. You can call the base class method directly using Base Class name itself without using the super() function
Continued The syntax is, BaseClassName.methodname(self, arguments) Notice the difference between super() function and the base class name in calling the method name. Use issubclass() function to check class inheritance. The syntax is, issubclass(DerivedClassName, BaseClassName) This function returns Boolean True if DerivedClassName is a derived class of base class BaseClassName. The DerivedClassName class is considered a subclass of itself. BaseClassName may be a tuple of classes, in which case every entry in BaseClassName will be checked. In any other case, a TypeError exception is raised
Program on multiple inheritance Python program to derive a new class movie from base class director and actor. Filename:c19.py Program to Demonstrate Multiple Inheritance with Method Overriding Filename:c20.py
Method resolution order When method overriding is used in multiple inheritance always the derived class invokes always its own class override method. To invoke overrided methods in base class solution is method resolution order What is MRO? In python, method resolution order defines the order in which the base classes are searched when executing a method. First, the method or attribute is searched within a class and then it follows the order we specified while inheriting. This order is also called Linearization of a class and set of rules are called MRO(Method Resolution Order).
continued Methods for Method Resolution Order(MRO) of a class: To get the method resolution order of a class we can use either __mro__ attribute or mro() method. By using these methods we can display the order in which methods are resolved. Filename:c20.py
Diamond problem/Deadly Diamond of Death Classes First, Second, Third, and Fourth are defined. Class Fourth inherits from both Second and Third classes. Class Second and Third inherit from class First. Hence class Fourth will have two copies of class First and is called diamond problem of multiple inheritance Program to illustrate diamond problem Filename:c21,c22
The Polymorphism Poly means many and morphism means forms. Polymorphism is one of the tenets of Object Oriented Programming (OOP). Polymorphism means that you can have multiple classes where each class implements the same variables or methods in different ways. Polymorphism takes advantage of inheritance in order to make this happen. A real-world example of polymorphism is suppose when if you are in classroom that time you behave like a student, when you are in market at that time you behave like a customer, when you are at your home at that time you behave like a son or daughter, such that same person is presented as having different behaviors
Programs on polymorphism Python program to illustrate polymorphism Filename:c24.py Write Python Program to Calculate Area and Perimeter of Different Shapes Using Polymorphism Filename:c25.py
Operator Overloading and Magic Methods Operator Overloading is a specific case of polymorphism, where different operators have different implementations depending on their arguments. A class can implement certain operations that are invoked by special syntax by defining methods with special names called “Magic Methods”. This is Python’s approach to operator overloading
Python magic methods or special functions for operator overloading Binary operators operator Magic Method + __add__(self, other) – __sub__(self, other) * __mul__(self, other) / __truediv__(self, other) // __floordiv__(self, other) % __mod__(self, other) ** __pow__(self, other) >> __rshift__(self, other) << __lshift__(self, other) & __and__(self, other) | __or__(self, other) ^ __xor__(self, other)
Comparison Operators : operator Magic Method < __LT__(SELF, OTHER) > __GT__(SELF, OTHER) <= __LE__(SELF, OTHER) >= __GE__(SELF, OTHER) == __EQ__(SELF, OTHER) != __NE__(SELF, OTHER)
Assignment Operators : operator Magic Method -= __ISUB__(SELF, OTHER) += __IADD__(SELF, OTHER) *= __IMUL__(SELF, OTHER) /= __IDIV__(SELF, OTHER) //= __IFLOORDIV__(SELF, OTHER) %= __IMOD__(SELF, OTHER) **= __IPOW__(SELF, OTHER) >>= __IRSHIFT__(SELF, OTHER) <<= __ILSHIFT__(SELF, OTHER) &= __IAND__(SELF, OTHER) |= __IOR__(SELF, OTHER) ^= __IXOR__(SELF, OTHER)
Unary Operators : operator Magic Method – __NEG__(SELF, OTHER) + __POS__(SELF, OTHER) ~ __INVERT__(SELF, OTHER)
Program on operator overloading Write Python Program to Create a Class Called as Complex and Implement __add__() Method to Add Two Complex Numbers. Display the Result by Overloading the + Operator Filename:c26.py Consider a Rectangle Class and Create Two Rectangle Objects. This Program Should Check Whether the Area of the First Rectangle is Greater than Second by Overloading > Operator Filename:

OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING

  • 1.
  • 2.
    Class and Objects Aclass is a blueprint from which individual objects are created. An object is a bundle of related state (variables) and behavior (methods). Objects contain variables, which represents the state of information about the thing you are trying to model, and the methods represent the behavior or functionality that you want it to have
  • 3.
    continued Variables refers toboth Instance variables and Class variables, unless explicitly specified. Class objects are often used to model the real-world objects that you find in everyday life. Objects are key to understanding object- oriented technology. Look around right now and you’ll find many examples of real-world objects: your dog, your desk, your television set, your bicycle. Real- world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming
  • 4.
    Creating Classes inPython Related variables and methods are grouped together in classes. The simplest form of class definition looks like this: class ClassName: <statement1> ------- <statement>
  • 5.
    continued Classes are definedby using the class keyword, followed by the ClassName and a colon. Class definitions must be executed before they have any effect. In practice, the statements inside a class definition will usually be function definitions, but few other statements are allowed. Because these functions are indented under a class, they are called methods. Methods are a special kind of function that is defined within a class. Python program to illustrate classes and object creation Filename:c1.py,c2.py
  • 6.
    Class mobile Let’s definea class called Mobile that has two methods associated with it one is receive_message() and another is send_message(). The first parameter in each of these methods is the word self. Self is a default variable which contains the memory address of the invoking object of the class. In the method definition, self doesn’t need to be the only parameter and it can have multiple parameters. Creating the Mobile class provided us with a blueprint for an object. Just because you have defined a class doesn’t mean you have created any Mobile objects. __init__ (self) is a special method called as constructor. It is implicitly called when object of the class is created
  • 7.
    Creating Objects inPython Object refers to a particular instance of a class where the object contains variables and methods defined in the class. Class objects support two kinds of operations: attribute references and instantiation. The act of creating an object from a class is called instantiation. The names in a class are referenced by objects and are called attribute references. There are two kinds of attribute references, data attributes and method attributes. Variables defined within the methods are called instance variables and are used to store data values. New instance variables are associated with each of the objects that are created for a class. These instance variables are also called data attributes. Method attributes are methods inside a class and are referenced by objects of a class. Attribute references use the standard dot notation syntax as supported in Python. • object_name.data_attribute_name • object_name.method_attribute_name() . The syntax for Class instantiation is, • object_name = ClassName(argument_1, argument_2, ….., argument_n) optional
  • 8.
    The Constructor Method Pythonuses a special method called a constructor method. Python allows you to define only one constructor per class. Also known as the __init__() method, it will be the first method definition of a class and its syntax is,
  • 9.
    continued The __init__() methoddefines and initializes the instance variables. It is invoked as soon as an object of a class is instantiated. The __init__() method for a newly created object is automatically executed with all of its parameters. The __init__() method is indeed a special method as other methods do not receive this treatment. The parameters for __init__() method are initialized with the arguments that you had passed during instantiation of the class object. Class methods that begin with a double underscore (__) are called special methods as they have special meaning. The number of arguments during the instantiation of the class object should be equivalent to the number of parameters in __init__() method (excluding the self parameter).
  • 10.
    Programs on classes Pythonprogram to create a class Mobile with attributes name, price and model. Use constructor to initialize the instance variable and display method to display the details of a mobile filename:c3.py Python program to create a class Student with attributes name, sem division and USN. Use to set() to initialize the attributes and get() method to display the details of a student Filename:c4.py Write Python Program to Calculate the Arc Length of an Angle by Assigning Values to the Radius and Angle Data Attributes of the class ArcLength Filename:c5.py
  • 11.
    Access specifiers By defaultall members are public Variable name or method name prefixed with single underscore(_) are treated as protected member self._name=‘raj’ def _display(self): Variable name or method name prefixed with double underscore(__) are treated as private member self.__name=‘raj’ def __display(self):
  • 12.
    continued Write Python Programto Simulate a Bank Account with private data attributes name and balance and protected methods depositMoney, withdrawMoney and showBalance filename:c6.py
  • 13.
    Classes with MultipleObjects Multiple objects for a class can be created while attaching a unique copy of data attributes and methods of the class to each of these objects. Define a class student with private data attributes name and marks. Read n student details and print student details along with grade obtained. Filename c7.py Write a python program to simulate bank operations using class concept Filename:c8.py
  • 14.
    Default parameters Python programto illustrate default parameters Filename:c9.py
  • 15.
    Using Objects asArguments An object can be passed to a calling function as an argument Python Program to Demonstrate Passing of an Object as an Argument to a Function Call filename:c10.py Given Three Points (x1, y1), (x2, y2) and (x3, y3), Write a Python Program to Check If they are Collinear using class concept Filename:c11.py Three points lie on the straight line if the area formed by the triangle of these three points is zero. So we will check if the area formed by the triangle is zero or not Formula for area of triangle is : 0.5 * [x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)]
  • 16.
    Objects as ReturnValues It is important to note that everything in Python is an object, including classes. In Python, “everything is an object” (that is, all values are objects) because Python does not include any primitive, unboxed values. Anything that can be used as a value (int, str, float, functions, modules, etc.) is implemented as an object. The id() function is used to find the identity of the location of the object in memory. The syntax for id() function is id(object) This function returns the “identity” of an object. This is an integer (or long integer), which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
  • 17.
    continued You can checkwhether an object is an instance of a given class or not by using the isinstance() function. The syntax for isinstance() function is, isinstance (object, classinfo) where the object is an object instance and classinfo can be a class, or a tuple containing classes, or other tuples. The isinstance() function returns a Boolean stating whether the object is an instance or subclass of another object.
  • 18.
    program Given the Coordinates(x, y) of a Center of a Circle and Its Radius, Write Python Program to Determine Whether the Point Lies Inside the Circle, On the Circle or Outside the Circle using class Circle Filename:c12.py The idea is compute distance of point from center. If distance is less than or equal to radius. the point is inside, else outside. If((x-cir_x)*(x-cir_x)+(y-cir_y)*(y-cir_y)==r*r Write Python Program to Compute the End Time, While Start Time and Duration are Given using a class Time Filename:c13.py
  • 19.
    Class Attributes versusData Attributes Generally speaking, Data attributes are instance variables that are unique to each object of a class, and Class attributes are class variables that is shared by all objects of a class. Program to Illustrate Class Variables and Instance Variables Filename:c14.py
  • 20.
    Encapsulation Encapsulation is oneof the fundamental concepts in object-oriented programming (OOP). Encapsulation is the process of combining variables that store data and methods that work on those variables into a single unit called class. In Encapsulation, the variables are not accessed directly. It is accessed through the methods present in the class. Encapsulation ensures that the object’s internal representation (its state and behavior) are hidden from the rest of the application. Thus, encapsulation makes the concept of data hiding possible. Given a point(x, y), Write Python Program to Find Whether it Lies in the First, Second, Third or Fourth Quadrant of x - y Plane filename:c15.py
  • 21.
    Inheritance Inheritance enables newclasses to receive or inherit variables and methods of existing classes. Inheritance is a way to express a relationship between classes. If you want to build a new class, which is already similar to one that already exists, then instead of creating a new class from scratch you can reference the existing class and indicate what is different by overriding some of its behavior or by adding some new functionality. A class that is used as the basis for inheritance is called a superclass or base class. A class that inherits from a base class is called a subclass or derived class. The terms parent class and child class are also acceptable terms to use respectively. A derived class inherits variables and methods from its base class while adding additional variables and methods of its own. Inheritance easily enables reusing of existing code.
  • 22.
    Continued The relationship betweenderived classes and base class using the phrase is-a, then that relationship is inheritance. For example, a lemon is-a citrus fruit, which is-a fruit. A shepherd is-a dog, which is-a animal. A guitar is-a steel-stringed instrument, which is-a musical instrument. If the is-a relationship does not exist between a derived class and base class, you should not use inheritance.
  • 23.
    The syntax fora derived class definition To create a derived class, you add a BaseClassName after theDerivedClassName within the parenthesis followed by a colon. The derived class is said to directly inherit from the listed base class.
  • 24.
    continued In place ofa base class name, other arbitrary expressions are also allowed. This can be useful, for example, when the base class is defined in another module:
  • 25.
    program Program to DemonstrateBase and Derived Class Relationship Without Using __init__() Method in a Derived Class Filename:c16.py
  • 26.
    Using super() Functionand Overriding Base Class Methods In a single inheritance, the built-in super() function can be used to refer to base classes without naming them explicitly, thus making the code more maintainable. If you need to access the data attributes from the base class in addition to the data attributes being specified in the derived class’s __init__() method, then you must explicitly call the base class __init__() method using super() yourself, since that will not happen automatically. However, if you do not need any data attributes from the base class, then no need to use super() function to invoke base class __init__() method. The syntax for using super() in derived class __init__() method definition looks like this: super().__init__(base_class_parameter(s)) Its usage is shown below. class DerivedClassName(BaseClassName): def __init__(self, derived_class_parameter(s), base_class_parameter(s)) super().__init__(base_class_parameter(s)) self.derived_class_instance_variable = derived_class_parameter
  • 27.
    program Program to Demonstratethe Use of super() Function filename:c17.py Define derived class Enggstudent from a base class Student with private attributes branch semester and division. Base class has private members name and USN. Override display method in base and derived class to display the details of a student Filename:c18.py
  • 28.
    Multiple Inheritances Python alsosupports a form of multiple inheritances. A derived class definition with multiple base classes looks like this: class DerivedClassName(Base_1, Base_2, Base_3): <statement-1> . . . <statement-N> Derived class DerivedClassName is inherited from multiple base classes, Base_1, Base_2, Base_3. For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy. Thus, if an attribute is not found in DerivedClassName, it is searched for in Base_1, then (recursively) in the base classes of Base_1, and if it was not found there, it would be searched for in Base_2, and so on. Even though multiple inheritances are available in Python programming language, it is not highly encouraged to use it as it is hard and error prone. You can call the base class method directly using Base Class name itself without using the super() function
  • 29.
    Continued The syntax is, BaseClassName.methodname(self,arguments) Notice the difference between super() function and the base class name in calling the method name. Use issubclass() function to check class inheritance. The syntax is, issubclass(DerivedClassName, BaseClassName) This function returns Boolean True if DerivedClassName is a derived class of base class BaseClassName. The DerivedClassName class is considered a subclass of itself. BaseClassName may be a tuple of classes, in which case every entry in BaseClassName will be checked. In any other case, a TypeError exception is raised
  • 30.
    Program on multipleinheritance Python program to derive a new class movie from base class director and actor. Filename:c19.py Program to Demonstrate Multiple Inheritance with Method Overriding Filename:c20.py
  • 31.
    Method resolution order Whenmethod overriding is used in multiple inheritance always the derived class invokes always its own class override method. To invoke overrided methods in base class solution is method resolution order What is MRO? In python, method resolution order defines the order in which the base classes are searched when executing a method. First, the method or attribute is searched within a class and then it follows the order we specified while inheriting. This order is also called Linearization of a class and set of rules are called MRO(Method Resolution Order).
  • 32.
    continued Methods for MethodResolution Order(MRO) of a class: To get the method resolution order of a class we can use either __mro__ attribute or mro() method. By using these methods we can display the order in which methods are resolved. Filename:c20.py
  • 33.
    Diamond problem/Deadly Diamondof Death Classes First, Second, Third, and Fourth are defined. Class Fourth inherits from both Second and Third classes. Class Second and Third inherit from class First. Hence class Fourth will have two copies of class First and is called diamond problem of multiple inheritance Program to illustrate diamond problem Filename:c21,c22
  • 34.
    The Polymorphism Poly meansmany and morphism means forms. Polymorphism is one of the tenets of Object Oriented Programming (OOP). Polymorphism means that you can have multiple classes where each class implements the same variables or methods in different ways. Polymorphism takes advantage of inheritance in order to make this happen. A real-world example of polymorphism is suppose when if you are in classroom that time you behave like a student, when you are in market at that time you behave like a customer, when you are at your home at that time you behave like a son or daughter, such that same person is presented as having different behaviors
  • 35.
    Programs on polymorphism Pythonprogram to illustrate polymorphism Filename:c24.py Write Python Program to Calculate Area and Perimeter of Different Shapes Using Polymorphism Filename:c25.py
  • 36.
    Operator Overloading andMagic Methods Operator Overloading is a specific case of polymorphism, where different operators have different implementations depending on their arguments. A class can implement certain operations that are invoked by special syntax by defining methods with special names called “Magic Methods”. This is Python’s approach to operator overloading
  • 37.
    Python magic methodsor special functions for operator overloading Binary operators operator Magic Method + __add__(self, other) – __sub__(self, other) * __mul__(self, other) / __truediv__(self, other) // __floordiv__(self, other) % __mod__(self, other) ** __pow__(self, other) >> __rshift__(self, other) << __lshift__(self, other) & __and__(self, other) | __or__(self, other) ^ __xor__(self, other)
  • 38.
    Comparison Operators : operatorMagic Method < __LT__(SELF, OTHER) > __GT__(SELF, OTHER) <= __LE__(SELF, OTHER) >= __GE__(SELF, OTHER) == __EQ__(SELF, OTHER) != __NE__(SELF, OTHER)
  • 39.
    Assignment Operators : operatorMagic Method -= __ISUB__(SELF, OTHER) += __IADD__(SELF, OTHER) *= __IMUL__(SELF, OTHER) /= __IDIV__(SELF, OTHER) //= __IFLOORDIV__(SELF, OTHER) %= __IMOD__(SELF, OTHER) **= __IPOW__(SELF, OTHER) >>= __IRSHIFT__(SELF, OTHER) <<= __ILSHIFT__(SELF, OTHER) &= __IAND__(SELF, OTHER) |= __IOR__(SELF, OTHER) ^= __IXOR__(SELF, OTHER)
  • 40.
    Unary Operators : operatorMagic Method – __NEG__(SELF, OTHER) + __POS__(SELF, OTHER) ~ __INVERT__(SELF, OTHER)
  • 41.
    Program on operatoroverloading Write Python Program to Create a Class Called as Complex and Implement __add__() Method to Add Two Complex Numbers. Display the Result by Overloading the + Operator Filename:c26.py Consider a Rectangle Class and Create Two Rectangle Objects. This Program Should Check Whether the Area of the First Rectangle is Greater than Second by Overloading > Operator Filename: