Category: Object Oriented Programming

  •  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)
  • Polymorphism

    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.

    If a 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

    There are four ways to implement polymorphism in Python −

    • Duck Typing
    • Operator Overloading
    • Method Overriding
    • Method Overloading
    implementing polymorphism

    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.

    Example

    In the code given below, we are practically demonstrating the concept of duck typing.

    classDuck:defsound(self):return"Quack, quack!"classAnotherBird:defsound(self):return"I'm similar to a duck!"defmakeSound(duck):print(duck.sound())# creating instances
    duck = Duck()
    anotherBird = AnotherBird()# calling methods
    makeSound(duck)   
    makeSound(anotherBird)

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

    Quack, quack!
    I'm similar to a duck!
    

    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.

    Example

    As an example of polymorphism given below, we have shape which is an abstract class. It is used as parent by two classes circle and rectangle. Both classes override parent’s draw() method in different ways.

    from abc import ABC, abstractmethod
    classshape(ABC):@abstractmethoddefdraw(self):"Abstract method"returnclasscircle(shape):defdraw(self):super().draw()print("Draw a circle")returnclassrectangle(shape):defdraw(self):super().draw()print("Draw a rectangle")return
    
    shapes =[circle(), rectangle()]for shp in shapes:
       shp.draw()

    Output

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

    Draw a circle
    Draw a rectangle
    

    The variable shp first refers to circle object and calls draw() method from circle class. In next iteration, it refers to rectangle object and calls draw() method from rectangle class. Hence draw() method in shape class is polymorphic.

    Overloading Operators in Python

    Suppose you have created a Vector class to represent two-dimensional vectors, what happens when you use the plus operator to add them? Most likely Python will yell at you.

    You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation −

    Example

    classVector:def__init__(self, a, b):
    
      self.a = a
      self.b = b
    def__str__(self):return'Vector (%d, %d)'%(self.a, self.b)def__add__(self,other):return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2)print(v1 + v2)

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

    Vector(7,8)
    

    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.

    Example

    In the following example, we are using the variable-length argument lists to achieve method overloading.

    defadd(*nums):returnsum(nums)# Call the function with different number of parameters
    result1 = add(10,25)
    result2 = add(10,25,35)print(result1)print(result2)

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

    35
    70
  • Inheritance

    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.

    If you 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.

    inheritance

    Creating a Parent Class

    The class whose attributes and methods are inherited is called as parent class. It is defined just like other classes i.e. using the class keyword.

    Syntax

    The syntax for creating a parent class is shown below −

    classParentClassName:{classbody}

    Creating a Child Class

    Classes that inherit from base classes are declared similarly to their parent class, however, we need to provide the name of parent classes within the parentheses.

    Syntax

    Following is the syntax of child class −

    classSubClassName(ParentClass1[, ParentClass2,...]):{sub classbody}

    Types of Inheritance

    In Python, inheritance can be divided in five different categories − 

    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    types of inheritance

    Python – Single Inheritance

    This is the simplest form of inheritance where a child class inherits attributes and methods from only one parent class.

    Example

    The below example shows single inheritance concept in Python −

    # parent classclassParent:defparentMethod(self):print("Calling parent method")# child classclassChild(Parent):defchildMethod(self):print("Calling child method")# instance of child
    c = Child()# calling method of child class
    c.childMethod()# calling method of parent class
    c.parentMethod()

    On running the above code, it will print the following result −

    Calling child method
    Calling parent method
    

    Python – 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.

    Syntax

    classparent1:#statementsclassparent2:#statementsclasschild(parent1, parent2):#statements

    Example

    Python’s standard library has a built-in divmod() function that returns a two-item tuple. First number is the division of two arguments, the second is the mod value of the two operands.

    This example tries to emulate the divmod() function. We define two classes division and modulus, and then have a div_mod class that inherits them.

    classdivision:def__init__(self, a,b):
    
      self.n=a
      self.d=b
    defdivide(self):return self.n/self.d classmodulus:def__init__(self, a,b):
      self.n=a
      self.d=b
    defmod_divide(self):return self.n%self.d
      
    classdiv_mod(division,modulus):def__init__(self, a,b):
      self.n=a
      self.d=b
    defdiv_and_mod(self):
      divval=division.divide(self)
      modval=modulus.mod_divide(self)return(divval, modval)</pre>

    The child class has a new method div_and_mod() which internally calls the divide() and mod_divide() methods from its inherited classes to return the division and mod values.

    x=div_mod(10,3)print("division:",x.divide())print("mod_division:",x.mod_divide())print("divmod:",x.div_and_mod())

    Output

    division: 3.3333333333333335
    mod_division: 1
    divmod: (3.3333333333333335, 1)
    

    Method Resolution Order (MRO)

    The term method resolution order is related to multiple inheritance in Python. In Python, inheritance may be spread over more than one levels. Let us say A is the parent of B, and B the parent for C. The class C can override the inherited method or its object may invoke it as defined in its parent. So, how does Python find the appropriate method to call.

    Each Python has a mro() method that returns the hierarchical order that Python uses to resolve the method to be called. The resolution order is from bottom of inheritance order to top.

    In our previous example, the div_mod class inherits division and modulus classes. So, the mro method returns the order as follows −

    [<class'__main__.div_mod'>,<class'__main__.division'>,<class'__main__.modulus'>,<class'object'>]

    Python - 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.

    Example

    In the following example, we are illustrating the working of multilevel inheritance.

    # parent classclassUniverse:defuniverseMethod(self):print("I am in the Universe")# child classclassEarth(Universe):defearthMethod(self):print("I am on Earth")# another child classclassIndia(Earth):defindianMethod(self):print("I am in India")# creating instance 
    person = India()# method calls
    person.universeMethod() 
    person.earthMethod() 
    person.indianMethod()

    When we execute the above code, it will produce the following result −

    I am in the Universe
    I am on Earth
    I am in India
    

    Python - Hierarchical Inheritance

    This type of inheritance contains multiple derived classes that are inherited from a single base class. This is similar to the hierarchy within an organization. 

    Example

    The following example illustrates hierarchical inheritance. Here, we have defined two child classes of Manager class.

    # parent classclassManager:defmanagerMethod(self):print("I am the Manager")# child classclassEmployee1(Manager):defemployee1Method(self):print("I am Employee one")# second child classclassEmployee2(Manager):defemployee2Method(self):print("I am Employee two")# creating instances 
    emp1 = Employee1()  
    emp2 = Employee2()# method calls
    emp1.managerMethod() 
    emp1.employee1Method()
    emp2.managerMethod() 
    emp2.employee2Method()

    On executing the above program, you will get the following output −

    I am the Manager
    I am Employee one
    I am the Manager
    I am Employee two
    

    Python - Hybrid Inheritance

    Combination of two or more types of inheritance is called as Hybrid Inheritance. For instance, it could be a mix of single and multiple inheritance.

    Example

    In this example, we have combined single and multiple inheritance to form a hybrid inheritance of classes.

    # parent classclassCEO:defceoMethod(self):print("I am the CEO")classManager(CEO):defmanagerMethod(self):print("I am the Manager")classEmployee1(Manager):defemployee1Method(self):print("I am Employee one")classEmployee2(Manager, CEO):defemployee2Method(self):print("I am Employee two")# creating instances 
    emp = Employee2()# method calls
    emp.managerMethod() 
    emp.ceoMethod()
    emp.employee2Method()

    On running the above program, it will give the below result −

    I am the Manager
    I am the CEO
    I am Employee two
    

    The super() function

    In Python, super() function allows you to access methods and attributes of the parent class from within a child class.

    Example

    In the following example, we create a parent class and access its constructor from a subclass using the super() function.

    # parent classclassParentDemo:def__init__(self, msg):
    
      self.message = msg
    defshowMessage(self):print(self.message)# child classclassChildDemo(ParentDemo):def__init__(self, msg):# use of super functionsuper().__init__(msg)# creating instance obj = ChildDemo("Welcome to Tutorialspoint!!") obj.showMessage()

    On executing, the above program will give the following result −

    Welcome to Tutorialspoint!!
    
  • Access Modifiers

    The Python access modifiers are used to restrict access to class members (i.e., variables and methods) from outside the class. There are three types of access modifiers namely public, protected, and private.

    • Public members − A class member is said to be public if it can be accessed from anywhere in the program.
    • Protected members − They are accessible from within the class as well as by classes derived from that class.
    • Private members − They can be accessed from within the class only.

    Usually, methods are defined as public and instance variable are private. This arrangement of private instance variables and public methods ensures implementation of principle of encapsulation.

    Access Modifiers in Python

    Unlike C++ and Java, Python does not use the Public, Protected and Private keywords to specify the type of access modifiers. By default, all the variables and methods in a Python class are public.

    Example

    Here, we have 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.

    classEmployee:'Common base class for all employees'def__init__(self, name="Bhavana", age=24):
    
      self.name = name
      self.age = age
    e1 = Employee() e2 = Employee("Bharat",25)print("Name: {}".format(e1.name))print("age: {}".format(e1.age))print("Name: {}".format(e2.name))print("age: {}".format(e2.age))

    It will produce the following output −

    Name: Bhavana
    age: 24
    Name: Bharat
    age: 25
    

    Python doesn’t enforce restrictions on accessing any instance variable or method. However, Python prescribes a convention of prefixing name of variable/method with single or double underscore to emulate behavior of protected and private access modifiers.

    • To indicate that an instance variable is private, prefix it with double underscore (such as “__age”).
    • To imply that a certain instance variable is protected, prefix it with single underscore (such as “_salary”).

    Another Example

    Let us modify the Employee class. Add another instance variable salary. Make ageprivate and salary as protected by prefixing double and single underscores respectively.

    classEmployee:def__init__(self, name, age, salary):
    
      self.name = name # public variable
      self.__age = age # private variable
      self._salary = salary # protected variabledefdisplayEmployee(self):print("Name : ", self.name,", age: ", self.__age,", salary: ", self._salary)
    e1=Employee("Bhavana",24,10000)print(e1.name)print(e1._salary)print(e1.__age)

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

    Bhavana
    10000
    Traceback (most recent call last):
     File "C:\Users\user\example.py", line 14, in <module>
      print (e1.__age)
    
        ^^^^^^^^
    AttributeError: 'Employee' object has no attribute '__age'

    Python displays AttributeError because __age is private, and not available for use outside the class.

    Name Mangling

    Python doesn’t block access to private data, it just leaves for the wisdom of the programmer, not to write any code that access 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 “__age” instance variable of “e1” object, change it to “e1._Employee__age”.

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

    print(e1._Employee__age)

    It now prints 24, the age of e1.

    Python Property Object

    Python’s standard library has a built-in property() function. It returns a property object. It acts as an interface to the instance variables of a Python class.

    The encapsulation principle of object-oriented programming requires that the instance variables should have a restricted private access. Python doesn’t have efficient mechanism for the purpose. The property() function provides an alternative.

    The property() function uses the getter, setter and delete methods defined in a class to define a property object for the class.

    Syntax

    property(fget=None, fset=None, fdel=None, doc=None)

    Parameters

    • fget − an instance method that retrieves value of an instance variable.
    • fset − an instance method that assigns value to an instance variable.
    • fdel − an instance method that removes an instance variable
    • fdoc − Documentation string for the property.

    The function uses getter and setter methods to return the property object.

    Getters and Setter Methods

    A getter method retrieves the value of an instance variable, usually named as get_varname, whereas the setter method assigns value to an instance variable − named as set_varname.

    Example

    Let us define getter methods get_name() and get_age(), and setters set_name() and set_age() in the Employee class.

    classEmployee:def__init__(self, name, age):
    
      self.__name = name
      self.__age = age
    defget_name(self):return self.__name defget_age(self):return self.__age defset_name(self, name):
      self.__name = name
      returndefset_age(self, age):
      self.__age=age
    e1=Employee("Bhavana",24)print("Name:", e1.get_name(),"age:", e1.get_age()) e1.set_name("Archana") e1.set_age(21)print("Name:", e1.get_name(),"age:", e1.get_age())

    It will produce the following output −

    Name: Bhavana age: 24
    Name: Archana age: 21
    

    The getter and setter methods can retrieve or assign value to instance variables. The property() function uses them to add property objects as class attributes.

    The name property is defined as −

    name =property(get_name, set_name,"name")

    Similarly, you can add the age property −

    age =property(get_age, set_age,"age")

    The advantage of the property object is that you can use to retrieve the value of its associated instance variable, as well as assign value.

    For example,

    print(e1.name) displays value of e1.__name
    e1.name ="Archana" assigns value to e1.__age
    

    Example

    The complete program with property objects and their use is given below −

    classEmployee:def__init__(self, name, age):
    
      self.__name = name
      self.__age = age
    defget_name(self):return self.__name defget_age(self):return self.__age defset_name(self, name):
      self.__name = name
      returndefset_age(self, age):
      self.__age=age
      return
    name =property(get_name, set_name,"name") age =property(get_age, set_age,"age") e1=Employee("Bhavana",24)print("Name:", e1.name,"age:", e1.age) e1.name ="Archana" e1.age =23print("Name:", e1.name,"age:", e1.age)

    It will produce the following output −

    Name: Bhavana age: 24
    Name: Archana age: 23
    
  •  Constructors

    Python constructor is an instance method in a class, that is automatically called whenever a new object of the class is created. The constructor’s role is to assign value to instance variables as soon as the object is declared.

    Python uses a special method called __init__() to initialize the instance variables for the object, as soon as it is declared.

    Creating a constructor in Python

    The __init__() method acts as a constructor. It needs a mandatory argument named self, which is the reference to the object.

    def__init__(self, parameters):#initialize instance variables

    The __init__() method as well as any instance method in a class has a mandatory parameter, self. However, you can give any name to the first parameter, not necessarily self.

    Types of Constructor in Python

    Python has two types of constructor −

    • Default Constructor
    • Parameterized Constructor

    Default Constructor in Python

    The Python constructor which does not accept any parameter other than self is called as default constructor.

    Example

    Let us define the constructor in the Employee class to initialize name and age as instance variables. We can then access these attributes through its object.

    classEmployee:'Common base class for all employees'def__init__(self):
    
      self.name ="Bhavana"
      self.age =24
    e1 = Employee()print("Name: {}".format(e1.name))print("age: {}".format(e1.age))

    It will produce the following output −

    Name: Bhavana
    age: 24
    

    For the above Employee class, each object we declare will have same value for its instance variables name and age. To declare objects with varying attributes instead of the default, define arguments for the __init__() method.

    Parameterized Constructor

    If a constructor is defined with multiple parameters along with self is called as parameterized constructor.

    Example

    In this example, the __init__() constructor has two formal arguments. We declare Employee objects with different values −

    classEmployee:'Common base class for all employees'def__init__(self, name, age):
    
      self.name = name
      self.age = age
    e1 = Employee("Bhavana",24) e2 = Employee("Bharat",25)print("Name: {}".format(e1.name))print("age: {}".format(e1.age))print("Name: {}".format(e2.name))print("age: {}".format(e2.age))

    It will produce the following output −

    Name: Bhavana
    age: 24
    Name: Bharat
    age: 25
    

    You can also assign default values to the formal arguments in the constructor so that the object can be instantiated with or without passing parameters.

    classEmployee:'Common base class for all employees'def__init__(self, name="Bhavana", age=24):
    
      self.name = name
      self.age = age
    e1 = Employee() e2 = Employee("Bharat",25)print("Name: {}".format(e1.name))print("age: {}".format(e1.age))print("Name: {}".format(e2.name))print("age: {}".format(e2.age))

    It will produce the following output −

    Name: Bhavana
    age: 24
    Name: Bharat
    age: 25
    

    Python – Instance Methods

    In addition to the __init__() constructor, there may be one or more instance methods defined in a class. A method with self as one of the formal arguments is called instance method, as it is called by a specific object.

    Example

    In the following example a displayEmployee() method has been defined as an instance method. It returns the name and age attributes of the Employee object that calls the method.

    classEmployee:def__init__(self, name="Bhavana", age=24):
    
      self.name = name
      self.age = age
    defdisplayEmployee(self):print("Name : ", self.name,", age: ", self.age) e1 = Employee() e2 = Employee("Bharat",25) e1.displayEmployee() e2.displayEmployee()

    It will produce the following output −

    Name : Bhavana , age: 24
    Name : Bharat , age: 25
    

    You can add, remove, or modify attributes of classes and objects at any time −

    # Add a 'salary' attribute
    emp1.salary =7000# Modify 'name' attribute
    emp1.name ='xyz'# Delete 'salary' attributedel emp1.salary 
    

    Instead of using the normal statements to access attributes, you can use the following functions −

    • The getattr(obj, name[, default]) − to access the attribute of object.
    • The hasattr(obj,name) − to check if an attribute exists or not.
    • The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.
    • The delattr(obj, name) − to delete an attribute.
    # Returns true if 'salary' attribute existsprint(hasattr(e1,'salary'))# Returns value of 'name' attributeprint(getattr(e1,'name'))# Set attribute 'salary' at 8setattr(e1,'salary',7000)# Delete attribute 'age'delattr(e1,'age')

    It will produce the following output −

    False
    Bhavana
    

    Python Multiple Constructors

    As mentioned earlier, we define the __init__() method to create a constructor. However, unlike other programming languages like C++ and Java, Python does not allow multiple constructors.

    If you try to create multiple constructors, Python will not throw an error, but it will only consider the last __init__() method in your class. Its previous definition will be overridden by the last one. 

    But, there is a way to achieve similar functionality in Python. We can overload constructors based on the type or number of arguments passed to the __init__() method. This will allow a single constructor method to handle various initialization scenarios based on the arguments provided.

    Example

    The following example shows how to achieve functionality similar to multiple constructors.

    classStudent:def__init__(self,*args):iflen(args)==1:
    
         self.name = args[0]eliflen(args)==2:
         self.name = args[0]
         self.age = args[1]eliflen(args)==3:
         self.name = args[0]
         self.age = args[1]
         self.gender = args[2]
            
    st1 = Student("Shrey")print("Name:", st1.name) st2 = Student("Ram",25)print(f"Name: {st2.name} and Age: {st2.age}") st3 = Student("Shyam",26,"M")print(f"Name: {st3.name}, Age: {st3.age} and Gender: {st3.gender}")

    When we run the above code, it will produce the following output −

    Name: Shrey
    Name: Ram and Age: 25
    Name: Shyam, Age: 26 and Gender: M
  • Static Methods

    What is Python Static Method?

    In Python, a static method is a type of method that does not require any instance to be called. It is very similar to the class method but the difference is that the static method doesn’t have a mandatory argument like reference to the object − self or reference to the class − cls.

    Static methods are used to access static fields of a given class. They cannot modify the state of a class since they are bound to the class, not instance.

    How to Create Static Method in Python?

    There are two ways to create Python static methods −

    • Using staticmethod() Function
    • Using @staticmethod Decorator

    Using staticmethod() Function

    Python’s standard library function named staticmethod() is used to create a static method. It accepts a method as an argument and converts it into a static method.

    Syntax

    staticmethod(method)

    Example

    In the Employee class below, the showcount() method is converted into a static method. This static method can now be called by its object or reference of class itself.

    classEmployee:
       empCount =0def__init__(self, name, age):
    
      self.__name = name
      self.__age = age
      Employee.empCount +=1# creating staticmethoddefshowcount():print(Employee.empCount)return
    counter =staticmethod(showcount) e1 = Employee("Bhavana",24) e2 = Employee("Rajesh",26) e3 = Employee("John",27) e1.counter() Employee.counter()

    Executing the above code will print the following result −

    3
    3
    

    Using @staticmethod Decorator

    The second way to create a static method is by using the Python @staticmethod decorator. When we use this decorator with a method it indicates to the Interpreter that the specified method is static.

    Syntax

    @staticmethoddefmethod_name():# your code

    Example

    In the following example, we are creating a static method using the @staticmethod decorator.

    classStudent:
       stdCount =0def__init__(self, name, age):
    
      self.__name = name
      self.__age = age
      Student.stdCount +=1# creating staticmethod@staticmethoddefshowcount():print(Student.stdCount)
    e1 = Student("Bhavana",24) e2 = Student("Rajesh",26) e3 = Student("John",27)print("Number of Students:") Student.showcount()

    Running the above code will print the following result −

    Number of Students:
    3
    

    Advantages of Static Method

    There are several advantages of using static method, which includes −

    • Since a static method cannot access class attributes, it can be used as a utility function to perform frequently re-used tasks.
    • We can invoke this method using the class name. Hence, it eliminates the dependency on the instances.
    • A static method is always predictable as its behavior remain unchanged regardless of the class state.
    • We can declare a method as a static method to prevent overriding.

  • Class Methods

    Methods belongs to an object of a class and used to perform specific operations. We can divide Python methods in three different categories, which are class method, instance method and static method.

    A Python class method is a method that is bound to the class and not to the instance of the class. It can be called on the class itself, rather than on an instance of the class. 

    Most of us often get class methods confused with static methods. Always remember, while both are called on the class, static methods do not have access to the “cls” parameter and therefore it cannot modify the class state.

    Unlike class method, the instance method can access the instance variables of the an object. It can also access the class variable as it is common to all the objects.

    Creating Class Methods in Python

    There are two ways to create class methods in Python −

    • Using classmethod() Function
    • Using @classmethod Decorator

    Using classmethod() Function

    Python has a built-in function classmethod() which transforms an instance method to a class method which can be called with the reference to the class only and not the object.

    Syntax

    classmethod(instance_method)

    Example

    In the Employee class, define a showcount() instance method with the “self” argument (reference to calling object). It prints the value of empCount. Next, transform the method to class method counter() that can be accessed through the class reference.

    classEmployee:
       empCount =0def__init__(self, name, age):
    
      self.__name = name
      self.__age = age
      Employee.empCount +=1defshowcount(self):print(self.empCount)
      
    counter =classmethod(showcount) e1 = Employee("Bhavana",24) e2 = Employee("Rajesh",26) e3 = Employee("John",27) e1.showcount() Employee.counter()

    Output

    Call showcount() with object and call count() with class, both show the value of employee count.

    3
    3
    

    Using @classmethod Decorator

    Use of @classmethod() decorator is the prescribed way to define a class method as it is more convenient than first declaring an instance method and then transforming it into a class method.

    Syntax

    @classmethoddefmethod_name():# your code

    Example

    The class method acts as an alternate constructor. Define a newemployee()class method with arguments required to construct a new object. It returns the constructed object, something that the __init__() method does.

    classEmployee:
    
    empCount =0def__init__(self, name, age):
        self.name = name
        self.age = age
        Employee.empCount +=1@classmethoddefshowcount(cls):print(cls.empCount)@classmethoddefnewemployee(cls, name, age):return cls(name, age)
    e1 = Employee("Bhavana",24) e2 = Employee("Rajesh",26) e3 = Employee("John",27) e4 = Employee.newemployee("Anil",21) Employee.showcount()

    There are four Employee objects now. If we run the above program, it will show the count of Employee object −

    4
    

    Access Class Attributes in Class Method 

    Class attributes are those variables that belong to a class and whose value is shared among all the instances of that class.

    To access class attributes within a class method, use the cls parameter followed by dot (.) notation and name of the attribute. 

    Example

    In this example, we are accessing a class attribute in class method.

    classCloth:# Class attribute
       price =4000@classmethoddefshowPrice(cls):return cls.price
    
    # Accessing class attributeprint(Cloth.showPrice())

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

    4000
    

    Dynamically Add Class Method to a Class

    The Python setattr() function is used to set an attribute dynamically. If you want to add a class method to a class, pass the method name as a parameter value to setattr() function.

    Example

    The following example shows how to add a class method dynamically to a Python class.

    classCloth:pass# class method@classmethoddefbrandName(cls):print("Name of the brand is Raymond")# adding dynamicallysetattr(Cloth,"brand_name", brandName)
    newObj = Cloth()
    newObj.brand_name()

    When we execute the above code, it will show the following output −

    Name of the brand is Raymond
    

    Dynamically Delete Class Methods

    The Python del operator is used to delete a class method dynamically. If you try to access the deleted method, the code will raise AttributeError.

    Example

    In the below example, we are deleting the class method named “brandName” using del operator.

    classCloth:# class method@classmethoddefbrandName(cls):print("Name of the brand is Raymond")# deleting dynamicallydel Cloth.brandName
    print("Method deleted")

    On executing the above code, it will show the following output −

    Method deleted