Blog

  •  Anonymous Class and Objects

    Python’s built-in type() function returns the class that an object belongs to. In Python, a class, both a built-in class or a user-defined class are objects of type class.

    Example

    Open Compiler

    classmyclass:def__init__(self):
    
      self.myvar=10return
      
    obj = myclass()print('class of int',type(int))print('class of list',type(list))print('class of dict',type(dict))print('class of myclass',type(myclass))print('class of obj',type(obj))

    It will produce the following output −

    class of int <class 'type'>
    class of list <class 'type'>
    class of dict <class 'type'>
    class of myclass <class 'type'>
    

    The type() has a three argument version as follows −

    Syntax

    newclass=type(name, bases, dict)
    

    Using above syntax, a class can be dynamically created. Three arguments of type function are −

    • name − name of the class which becomes __name__ attribute of new class
    • bases − tuple consisting of parent classes. Can be blank if not a derived class
    • dict − dictionary forming namespace of the new class containing attributes and methods and their values.

    Create an Anonymous Class

    We can create an anonymous class with the above version of type() function. The name argument is a null string, second argument is a tuple of one class the object class (note that each class in Python is inherited from object class). We add certain instance variables as the third argument dictionary. We keep it empty for now.

    anon=type('',(object,),{})
    
    Create an Anonymous Object
    
    To create an object of this anonymous class −
    
    obj = anon()
    print ("type of obj:", type(obj))
    The result shows that the object is of anonymous class
    
    type of obj: <class '__main__.'>
    Anonymous Class and Object Example
    
    We can also add instance variables and instance methods dynamically. Take a look at this example −
    
    def getA(self):
       return self.a
    obj = type('',(object,),{'a':5,'b':6,'c':7,'getA':getA,'getB':lambda self : self.b})()
    print (obj.getA(), obj.getB())
    It will produce the following output −
    
    5 6

  • Inner Classes

    Inner Class in Python

    A class defined inside another class is known as an inner class in Python. Sometimes inner class is also called nested class. If the inner class is instantiated, the object of inner class can also be used by the parent class. Object of inner class becomes one of the attributes of the outer class. Inner class automatically inherits the attributes of the outer class without formally establishing inheritance.

    Syntax

    classouter:def__init__(self):passclassinner:def__init__(self):pass

    An inner class lets you group classes. One of the advantages of nesting classes is that it becomes easy to understand which classes are related. The inner class has a local scope. It acts as one of the attributes of the outer class.

    Example

    In the following code, we have student as the outer class and subjects as the inner class. The __init__() constructor of student initializes name attribute and an instance of subjects class. On the other hand, the constructor of inner subjects class initializes two instance variables sub1, sub2.

    A show() method of outer class calls the method of inner class with the object that has been instantiated.

    classstudent:def__init__(self):
    
      self.name ="Ashish"
      self.subs = self.subjects()returndefshow(self):print("Name:", self.name)
      self.subs.display()classsubjects:def__init__(self):
         self.sub1 ="Phy"
         self.sub2 ="Che"returndefdisplay(self):print("Subjects:",self.sub1, self.sub2)
         
    s1 = student() s1.show()

    When you execute this code, it will produce the following output −

    Name: Ashish
    Subjects: Phy Che
    

    It is quite possible to declare an object of outer class independently, and make it call its own display() method.

    sub = student().subjects().display()

    It will list out the subjects.

    Types of Inner Class

    In Python, inner classes are of two types −

    • Multiple Inner Class
    • Multilevel Inner Class

    Multiple Inner Class

    In multiple inner class, a single outer class contains more than one inner class. Each inner class works independently but it can interact with the members of outer class.

    Example

    In the below example, we have created an outer class named Organization and two inner classes.

    classOrganization:def__init__(self):
    
      self.inner1 = self.Department1()
      self.inner2 = self.Department2()defshowName(self):print("Organization Name: Tutorials Point")classDepartment1:defdisplayDepartment1(self):print("In Department 1")classDepartment2:defdisplayDepartment2(self):print("In Department 2")# instance of OuterClass
    outer = Organization()# Calling show method outer.showName()# InnerClass instance 1 inner1 = outer.inner1 # Calling display method inner1.displayDepartment1()# InnerClass instance 2 inner2 = outer.inner2 # Calling display method inner2.displayDepartment2()

    On executing, this code will produce the following output −

    Organization Name: Tutorials Point
    In Department 1
    In Department 2
    

    Multilevel Inner Class

    It refers to an inner class that itself contains another inner class. It creates multiple levels of nested classes.

    Example

    The following code explains the working of Multilevel Inner Class in Python −

    classOrganization:def__init__(self):
    
      self.inner = self.Department()defshowName(self):print("Organization Name: Tutorials Point")classDepartment:def__init__(self):
         self.innerTeam = self.Team1()defdisplayDep(self):print("In Department")classTeam1:defdisplayTeam(self):print("Team 1 of the department")# instance of outer class                
    outer = Organization()# call the method of outer class outer.showName()# Inner Class instance inner = outer.inner inner.displayDep()# Access Team1 instance innerTeam = inner.innerTeam # Calling display method innerTeam.displayTeam()

    When you run the above code, it will produce the below output −

    Organization Name: Tutorials Point
    In Department
    Team 1 of the department
  • Packages

    In Python, the module is a Python script with a .py extension and contains objects such as classes, functions, etc. Packages in Python extend the concept of the modular approach further. The package is a folder containing one or more module files; additionally, a special file “__init__.py” file may be empty but may contain the package list.

    Create a Python Package

    Let us create a Python package with the name mypackage. Follow the steps given below −

    • Create an outer folder to hold the contents of mypackage. Let its name be packagedemo.
    • Inside it, create another folder mypackage. This will be the Python package we are going to construct. Two Python modules areafunctions.py and mathfunctions.py will be created inside mypackage.
    • Create an empty “__.init__.py” file inside mypackage folder.
    • Inside the outer folder, we shall later store a Python script example.py to test our package.

    The file/folder structure should be as shown below −

    folder_structure

    Using your favorite code editor, save the following two Python modules in mypackage folder.

    Example to Create a Python Package

    # mathfunctions.pydefsum(x,y):
       val = x+y
       return val
       
    defaverage(x,y):
       val =(x+y)/2return val
    
    defpower(x,y):
       val = x**y
       return val
    

    Create another Python script −

    # areafunctions.pydefrectangle(w,h):
       area = w*h
       return area
       
    defcircle(r):import math
       area = math.pi*math.pow(r,2)return area
    

    Let us now test the myexample package with the help of a Python script above this package folder. Refer to the folder structure above.

    #example.pyfrom mypackage.areafunctions import rectangle
    print("Area :", rectangle(10,20))from mypackage.mathsfunctions import average
    print("average:", average(10,20))

    This program imports functions from mypackage. If the above script is executed, you should get following output −

    Area : 200
    average: 15.0
    Define Package List

    You can put selected functions or any other resources from the package in the "__init__.py" file. Let us put the following code in it.

    from .areafunctions import circle
    from .mathsfunctions import sum, power
    To import the available functions from this package, save the following script as testpackage.py, above the package folder as before.

    Example to Define a Package List

    #testpackage.py
    from mypackage import power, circle

    print ("Area of circle:", circle(5))
    print ("10 raised to 2:", power(10,2))
    It will produce the following output −

    Area of circle: 78.53981633974483
    10 raised to 2: 100
    Package Installation

    Right now, we are able to access the package resources from a script just above the package folder. To be able to use the package anywhere in the file system, you need to install it using the PIP utility.

    First of all, save the following script in the parent folder, at the level of package folder.

    #setup.py
    from setuptools import setup
    setup(name='mypackage',
    version='0.1',
    description='Package setup script',
    url='#',
    author='anonymous',
    author_email='[email protected]',
    license='MIT',
    packages=['mypackage'],
    zip_safe=False)
    Run the PIP utility from command prompt, while remaining in the parent folder.

    C:\Users\user\packagedemo>pip3 install .
    Processing c:\users\user\packagedemo
    Preparing metadata (setup.py) ... done
    Installing collected packages: mypackage
    Running setup.py install for mypackage ... done
    Successfully installed mypackage-0.1
    You should now be able to import the contents of the package in any environment.

    C:\Users>python
    Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import mypackage
    >>> mypackage.circle(5)
    78.53981633974483
  •  Interfaces

    In software engineering, an interface is a software architectural pattern. It is similar to a class but its methods just have prototype signature definition without any executable code or implementation body. The required functionality must be implemented by the methods of any class that inherits the interface.

    The method defined without any executable code is known as abstract method.

    Interfaces in Python

    In languages like Java and Go, there is keyword called interface which is used to define an interface. Python doesn’t have it or any similar keyword. It uses abstract base classes (in short ABC module) and @abstractmethod decorator to create interfaces. 

    NOTE: In Python, abstract classes are also created using ABC module.

    An abstract class and interface appear similar in Python. The only difference in two is that the abstract class may have some non-abstract methods, while all methods in interface must be abstract, and the implementing class must override all the abstract methods.

    Rules for implementing Python Interfaces

    We need to consider the following points while creating and implementing interfaces in Python −

    • Methods defined inside an interface must be abstract. 
    • Creating object of an interface is not allowed.
    • A class implementing an interface needs to define all the methods of that interface.
    • In case, a class is not implementing all the methods defined inside the interface, the class must be declared abstract. 

    Ways to implement Interfaces in Python

    We can create and implement interfaces in two ways −

    • Formal Interface
    • Informal Interface

    Formal Interface

    Formal interfaces in Python are implemented using abstract base class (ABC). To use this class, you need to import it from the abc module.

    Example

    In this example, we are creating a formal interface with two abstract methods.

    from abc import ABC, abstractmethod
    
    # creating interfaceclassdemoInterface(ABC):@abstractmethoddefmethod1(self):print("Abstract method1")return@abstractmethoddefmethod2(self):print("Abstract method1")return

    Let us provide a class that implements both the abstract methods.

    # class implementing the above interfaceclassconcreteclass(demoInterface):defmethod1(self):print("This is method1")returndefmethod2(self):print("This is method2")return# creating instance      
    obj = concreteclass()# method call
    obj.method1()
    obj.method2()

    Output

    When you execute this code, it will produce the following output −

    This is method1
    This is method2
    

    Informal Interface

    In Python, the informal interface refers to a class with methods that can be overridden. However, the compiler cannot strictly enforce the implementation of all the provided methods. 

    This type of interface works on the principle of duck typing. It allows us to call any method on an object without checking its type, as long as the method exists.

    Example

    In the below example, we are demonstrating the concept of informal interface.

    classdemoInterface:defdisplayMsg(self):passclassnewClass(demoInterface):defdisplayMsg(self):print("This is my message")# creating instance      
    obj = newClass()# method call
    obj.displayMsg()

    Output

    On running the above code, it will produce the following output −

    This is my message
    
  • Encapsulation

    Encapsulation is the process of bundling attributes and methods within a single unit. It is one of the main pillars on which the object-oriented programmingparadigm is based.

    We know that a class is a user-defined prototype for an object. It defines a set of data members and methods, capable of processing the data.

    According to the principle of data encapsulation, the data members that describe an object are hidden from the environment external to the class. They can only be accessed through the methods within the same class. Methods themselves on the other hand are accessible from outside class context. Hence, object data is said to be encapsulated by the methods. In this way, encapsulation prevents direct access to the object data.

    Implementing Encapsulation in Python

    Languages such as C++ and Java use access modifiers to restrict access to class members (i.e., variables and methods). These languages have keywords public, protected, and private to specify the type of access.

    A class member is said to be public if it can be accessed from anywhere in the program. Private members are allowed to be accessed from within the class only. Usually, methods are defined as public, and instance variables are private. This arrangement of private instance variables and public methods ensures the implementation of encapsulation.

    Unlike these languages, Python has no provision to specify the type of access that a class member may have. By default, all the variables and methods in a Python class are public, as demonstrated by the following example.

    Example 1

    Here, we have an Employee class with instance variables, name and age. An object of this class has these two attributes. They can be directly accessed from outside the class, because they are public.

    classStudent:def__init__(self, name="Rajaram", marks=50):
    
      self.name = name
      self.marks = marks
    s1 = Student() s2 = Student("Bharat",25)print("Name: {} marks: {}".format(s1.name, s2.marks))print("Name: {} marks: {}".format(s2.name, s2.marks))

    It will produce the following output −

    Name: Rajaram marks: 50
    Name: Bharat marks: 25
    

    In the above example, the instance variables are initialized inside the class. However, there is no restriction on accessing the value of instance variables from outside the class, which is against the principle of encapsulation.

    Although there are no keywords to enforce visibility, Python has a convention of naming the instance variables in a peculiar way. In Python, prefixing name of a variable/method with a single or double underscore to emulate the behavior of protected and private access modifiers.

    If a variable is prefixed by a single double underscore (such as “__age“), the instance variable is private, similarly if a variable name is prefixed with a single underscore (such as “_salary“)

    Example 2

    Let us modify the Student class. Add another instance variable salary. Make name private and marks as private by prefixing double underscores to them.

    classStudent:def__init__(self, name="Rajaram", marks=50):
    
      self.__name = name
      self.__marks = marks
    defstudentdata(self):print("Name: {} marks: {}".format(self.__name, self.__marks))
      
    s1 = Student() s2 = Student("Bharat",25) s1.studentdata() s2.studentdata()print("Name: {} marks: {}".format(s1.__name, s2.__marks))print("Name: {} marks: {}".format(s2.__name, __s2.marks))

    When you run this code, it will produce the following output −

    Name: Rajaram marks: 50
    Name: Bharat marks: 25
    Traceback (most recent call last):
     File "C:\Python311\hello.py", line 14, in <module>
      print ("Name: {} marks: {}".format(s1.__name, s2.__marks))
    AttributeError: 'Student' object has no attribute '__name'
    

    The above output makes it clear that the instance variables name and age, can be accessed by a method declared inside the class (the studentdata() method), but the double underscores prefix makes the variables private, and hence, accessing them outside the class is restricted which raises Attribute error.

    What is Name Mangling?

    Python doesn’t block access to private data entirely. It just leaves it to the wisdom of the programmer, not to write any code that accesses it from outside the class. You can still access the private members by Python’s name mangling technique.

    Name mangling is the process of changing name of a member with double underscore to the form object._class__variable. If so required, it can still be accessed from outside the class, but the practice should be refrained.

    In our example, the private instance variable “__name” is mangled by changing it to the format

    obj._class__privatevar
    

    So, to access the value of “__marks” instance variable of “s1” object, change it to “s1._Student__marks”.

    Change the print() statement in the above program to −

    print(s1._Student__marks)

    It now prints 50, the marks of s1.

    Hence, we can conclude that Python doesn’t implement encapsulation exactly as per the theory of object-oriented programming. It adapts a more mature approach towards it by prescribing a name convention and letting the programmer use name mangling if it is really required to have access to private data in the public scope.

  • Abstraction

    Abstraction is one of the important principles of object-oriented programming. It refers to a programming approach by which only the relevant data about an object is exposed, hiding all the other details. This approach helps in reducing the complexity and increasing the efficiency of application development.

    Types of Python Abstraction

    There are two types of abstraction. One is data abstraction, wherein the original data entity is hidden via a data structure that can internally work through the hidden data entities. Another type is called process abstraction. It refers to hiding the underlying implementation details of a process.

    Python Abstract Class

    In object-oriented programming terminology, a class is said to be an abstract class if it cannot be instantiated, that is you can have an object of an abstract class. You can however use it as a base or parent class for constructing other classes.

    Create an Abstract Class

    To create an abstract class in Python, it must inherit the ABC class that is defined in the ABC module. This module is available in Python’s standard library. Moreover, the class must have at least one abstract method. Again, an abstract method is the one which cannot be called but can be overridden. You need to decorate it with @abstractmethod decorator.

    Example: Create an Absctract Class

    from abc import ABC, abstractmethod
    classdemo(ABC):@abstractmethoddefmethod1(self):print("abstract method")returndefmethod2(self):print("concrete method")

    The demo class inherits ABC class. There is a method1() which is an abstract method. Note that the class may have other non-abstract (concrete) methods.

    If you try to declare an object of demo class, Python raises TypeError −

       obj = demo()
    
         ^^^^^^
    TypeError: Can't instantiate abstract class demo with abstract method method1

    The demo class here may be used as parent for another class. However, the child class must override the abstract method in parent class. If not, Python throws this error −

    TypeError: Can't instantiate abstract class concreteclass with abstract method method1
    

    Abstract Method Overriding

    Hence, the child class with the abstract method overridden is given in the following example −

    Example

    from abc import ABC, abstractmethod
    classdemoclass(ABC):@abstractmethoddefmethod1(self):print("abstract method")returndefmethod2(self):print("concrete method")classconcreteclass(democlass):defmethod1(self):super().method1()return
    
      
    obj = concreteclass() obj.method1() obj.method2()

    Output

    When you execute this code, it will produce the following output −

    abstract method
    concrete method
  •  Dynamic Typing

    One of the standout features of Python language is that it is a dynamically typed language. The compiler-based languages C/C++, Java, etc. are statically typed. Let us try to understand the difference between static typing and dynamic typing.

    In a statically typed language, each variable and its data type must be declared before assigning it a value. Any other type of value is not acceptable to the compiler, and it raises a compile-time error.

    Let us take the following snippet of a Java program −

    public classMyClass{
       public static void main(String args[]){int var;
    
      var="Hello";
      
      System.out.println("Value of var = "+ var);}}</pre>

    Here, var is declared as an integer variable. When we try to assign it a string value, the compiler gives the following error message −

    /MyClass.java:4: error: incompatible types: String cannot be converted to int
       x="Hello";
    
     ^
    1 error

    Why Python is Called Dynamically Typed?

    variable in Python is only a label, or reference to the object stored in the memory, and not a named memory location. Hence, the prior declaration of type is not needed. Because it's just a label, it can be put on another object, which may be of any type.

    In Java, the type of the variable decides what it can store and what not. In Python, it is the other way around. Here, the type of data (i.e. object) decides the type of the variable. To begin with, let us store a string in the variable in check its type.

    >>> var="Hello">>>print("id of var is ",id(var))id of var is2822590451184>>>print("type of var is ",type(var))type of var is<class'str'>

    So, var is of string type. However, it is not permanently bound. It's just a label; and can be assigned to any other type of object, say a float, which will be stored with a different id() −

    >>> var=25.50>>>print("id of var is ",id(var))id of var is2822589562256>>>print("type of var is ",type(var))type of var is<class'float'>

    or a tuple. The var label now sits on a different object.

    >>> var=(10,20,30)>>>print("id of var is ",id(var))id of var is2822592028992>>>print("type of var is ",type(var))type of var is<class'tuple'>

    We can see that the type of var changes every time it refers to a new object. That's why Python is a dynamically typed language.

    Dynamic typing feature of Python makes it flexible compared to C/C++ and Java. However, it is prone to runtime errors, so the programmer has to be careful.

  • Dynamic Binding

    In object-oriented programming, the concept of dynamic binding is closely related to polymorphism. In Python, dynamic binding is the process of resolving a method or attribute at runtime, instead of at compile time.

    According to the polymorphism feature, different objects respond differently to the same method call based on their implementations. This behavior is achieved through method overriding, where a subclass provides its implementation of a method defined in its superclass.

    The Python interpreter determines which is the appropriate method or attribute to invoke based on the object’s type or class hierarchy at runtime. This means that the specific method or attribute to be called is determined dynamically, based on the actual type of the object.

    Example

    The following example illustrates dynamic binding in Python −

    Open Compiler

    classshape:defdraw(self):print("draw method")returnclasscircle(shape):defdraw(self):print("Draw a circle")returnclassrectangle(shape):defdraw(self):print("Draw a rectangle")return
    
    shapes =[circle(), rectangle()]for shp in shapes:
       shp.draw()

    It will produce the following output −

    Draw a circle
    Draw a rectangle
    

    As you can see, the draw() method is bound dynamically to the corresponding implementation based on the object’s type. This is how dynamic binding is implemented in Python.

    Duck Typing

    Another concept closely related to dynamic binding is duck typing. Whether an object is suitable for a particular use is determined by the presence of certain methods or attributes, rather than its type. This allows for greater flexibility and code reuse in Python.

    Duck typing is an important feature of dynamic typing languages like Python(PerlRubyPHPJavascript, etc.) that focuses on an object’s behavior rather than its specific type. According to the “duck typing” concept, “If it walks like a duck and quacks like a duck, then it must be a duck.”

    Duck typing allows objects of different types to be used interchangeably as long as they have the required methods or attributes. The goal is to promote flexibility and code reuse. It is a broader concept that emphasizes object behavior and interface rather than formal types.

    Here is an example of duck typing −

    Open Compiler

    classcircle:defdraw(self):print("Draw a circle")returnclassrectangle:defdraw(self):print("Draw a rectangle")returnclassarea:defarea(self):print("calculate area")returndefduck_function(obj):
       obj.draw()
    
    objects =[circle(), rectangle(), area()]for obj in objects:
       duck_function(obj)

    It will produce the following output −

    Draw a circle
    Draw a rectangle
    Traceback (most recent call last):
     File "C:\Python311\hello.py", line 21, in <module>
      duck_function(obj)
     File "C:\Python311\hello.py", line 17, in duck_function
     obj.draw()
    AttributeError: 'area' object has no attribute 'draw'
    

    The most important idea behind duck typing is that the duck_function()doesn’t care about the specific types of objects it receives. It only requires the objects to have a draw() method. If an object “quacks like a duck” by having the necessary behavior, it is treated as a “duck” for the purpose of invoking the draw() method.

    Thus, in duck typing, the focus is on the object’s behavior rather than its explicit type, allowing different types of objects to be used interchangeably as long as they exhibit the required behavior.

  •  Method Overloading

    Method overloading is a feature of object-oriented programming where a class can have multiple methods with the same name but different parameters. To overload method, we must change the number of parameters or the type of parameters, or both.

    Method Overloading in Python

    Unlike other programming languages like Java, C++, and C#, Python does not support the feature of method overloading by default. However, there are alternative ways to achieve it.

    Example

    If you define a method multiple times as shown in the below code, the last definition will override the previous ones. Therefore, this way of achieving method overloading in Python generates error.

    classexample:defadd(self, a, b):
    
      x = a+b
      return x
    defadd(self, a, b, c):
      x = a+b+c
      return x
    obj = example()print(obj.add(10,20,30))print(obj.add(10,20))

    The first call to add() method with three arguments is successful. However, calling add() method with two arguments as defined in the class fails.

    60
    Traceback (most recent call last):
     File "C:\Users\user\example.py", line 12, in <module>
      print (obj.add(10,20))
    
         ^^^^^^^^^^^^^^
    TypeError: example.add() missing 1 required positional argument: 'c'

    The output tells you that Python considers only the latest definition of add() method, discarding the earlier definitions.

    To simulate method overloading, we can use a workaround by defining default value to method arguments as None, so that it can be used with one, two or three arguments.

    Example

    The below example shows how to achieve method overloading in Python −

    classexample:defadd(self, a =None, b =None, c =None):
    
      x=0if a !=Noneand b !=Noneand c !=None:
         x = a+b+c
      elif a !=Noneand b !=Noneand c ==None:
         x = a+b
      return x
    obj = example()print(obj.add(10,20,30))print(obj.add(10,20))

    It will produce the following output −

    60
    30
    

    With this workaround, we are able to incorporate method overloading in Python class.

  • Method Overriding

    Method Overriding in Python

    The Python method overriding refers to defining a method in a subclass with the same name as a method in its superclass. In this case, the Python interpreter determines which method to call at runtime based on the actual object being referred to.

    You can always override your parent class methods. One reason for overriding parent’s methods is that you may want special or different functionality in your subclass.

    Example

    In the code below, we are overriding a method named myMethod of Parent class.

    # define parent classclassParent:defmyMethod(self):print('Calling parent method')# define child classclassChild(Parent):defmyMethod(self):print('Calling child method')# instance of child
    c = Child()# child calls overridden method
    c.myMethod()

    When the above code is executed, it produces the following output −

    Calling child method
    

    To understand Method Overriding in Python, let us take another example. We use following Employee class as parent class −

    classEmployee:def__init__(self,nm, sal):
    
      self.name=nm
      self.salary=sal
    defgetName(self):return self.name defgetSalary(self):return self.salary

    Next, we define a SalesOfficer class that uses Employee as parent class. It inherits the instance variables name and salary from the parent. Additionally, the child class has one more instance variable incentive.

    We shall use built-in function super() that returns reference of the parent class and call the parent constructor within the child constructor __init__() method.

    classSalesOfficer(Employee):def__init__(self,nm, sal, inc):super().__init__(nm,sal)
    
      self.incnt=inc
    defgetSalary(self):return self.salary+self.incnt

    The getSalary() method is overridden to add the incentive to salary.

    Example

    Declare the object of parent and child classes and see the effect of overriding. Complete code is below −

    classEmployee:def__init__(self,nm, sal):
    
      self.name=nm
      self.salary=sal
    defgetName(self):return self.name defgetSalary(self):return self.salary classSalesOfficer(Employee):def__init__(self,nm, sal, inc):super().__init__(nm,sal)
      self.incnt=inc
    defgetSalary(self):return self.salary+self.incnt e1=Employee("Rajesh",9000)print("Total salary for {} is Rs {}".format(e1.getName(),e1.getSalary())) s1=SalesOfficer('Kiran',10000,1000)print("Total salary for {} is Rs {}".format(s1.getName(),s1.getSalary()))

    When you execute this code, it will produce the following output −

    Total salary for Rajesh is Rs 9000
    Total salary for Kiran is Rs 11000
    Base Overridable Methods

    The following table lists some generic functionality of the object class, which is the parent class for all Python classes. You can override these methods in your own class −

    Sr.No Method, Description & Sample Call
    1
    __init__ ( self [,args...] )
    Constructor (with any optional arguments)
    Sample Call : obj = className(args)
    2
    __del__( self )
    Destructor, deletes an object
    Sample Call : del obj
    3
    __repr__( self )
    Evaluatable string representation
    Sample Call : repr(obj)
    4
    __str__( self )
    Printable string representation
    Sample Call : str(obj)