Author: saqibkhan

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

    Open Compiler

    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 −

    Open Compiler

    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.

    Implement Method Overloading Using MultipleDispatch

    Python’s standard library doesn’t have any other provision for implementing method overloading. However, we can use a dispatch function from a third-party module named MultipleDispatch for this purpose.

    First, you need to install the Multipledispatch module using the following command −

    pip install multipledispatch
    

    This module has a @dispatch decorator. It takes the number of arguments to be passed to the method to be overloaded. Define multiple copies of add() method with @dispatch decorator as below −

    Example

    In this example, we are using multipledispatch to overload a method in Python.

    from multipledispatch import dispatch
    classexample:@dispatch(int,int)defadd(self, a, b):
    
      x = a+b
      return x
    @dispatch(int,int,int)defadd(self, a, b, c):
      x = a+b+c
      return x
    obj = example()print(obj.add(10,20,30))print(obj.add(10,20))

    Output

    60
    30
  • 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.

    Open Compiler

    # 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 −

    Open Compiler

    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.NoMethod, Description & Sample Call
    1__init__ ( self [,args…] )Constructor (with any optional arguments)Sample Call : obj = className(args)
    2__del__( self )Destructor, deletes an objectSample Call : del obj
    3__repr__( self )Evaluatable string representationSample Call : repr(obj)
    4__str__( self )Printable string representationSample 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

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    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.

    Open Compiler

    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.

    Open Compiler

    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

    Open Compiler

    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.

    Open Compiler

    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}

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    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 −

    Open Compiler

    # 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)</code></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.

    Open Compiler

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

    Open Compiler

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

    Open Compiler

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

    Open Compiler

    # 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!!
  • Type Casting

    The term “Type Casting” refers to conversion of one type of data to another. Since PHP is a weakly typed language, the parser coerces certain data types into others while performing certain operations. For example, a string having digits is converted to integer if it is one of the operands involved in the addition operation.

    Implicit Type Casting

    Here is an example of coercive or implicit type casting −

    Open Compiler

    <?php
       $a = 10;
       $b = '20';
       $c = $a+$b;
       echo "c = " . $c;
    ?>

    In this case, $b is a string variable, cast into an integer to enable addition. It will produce the following output −

    c = 30
    

    Let’s take another example. Here, an integer variable $a is converted to a string so that it is concatenated with a string variable.

    Open Compiler

    <?php
       $a = 10;
       $b = '20';
       $c = $a.$b;
       echo "c = " . $c;
    ?>

    It will produce the following output −

    c = 1020
    

    In addition to such coercive type conversion, there are other ways to explicitly cast one type of data to other. You can use PHP’s type casting operators or type casting functions for this purpose.

    Type Casting Operators

    To convert an expression of one type to another, you need to put the data type of the latter in parenthesis before the expression.

    $var=(type)expr;

    Some of the type casting operators in PHP are −

    • (int) or (integer) casts to an integer
    • (bool) or (boolean) casts to a boolean
    • (float) or (double) or (real) casts to a float
    • (string) casts to a string
    • (array) casts to an array
    • (object) casts to an object

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Casting to Integer

    You can easily convert a float value to an integer. Take a look at the following example −

    Open Compiler

    <?php
       $a = 9.99;
       $b = (int)$a;
       var_dump($b);
    ?>

    It will produce the following output −

    int(9)
    

    Note that the float value is not rounded to the nearest integer; instead it just returns the integer part.

    String to Integer Conversion

    The (int) operator also coverts a string to integer. The conversion is straightforward if the string consists of just digits.

    Open Compiler

    <?php
       $a = "99";
       $b = (int)$a;
       var_dump($b);
    ?>

    Here, you will get the following output −

    int(99)
    

    Even if the string contains a floating point number, the (int) operator returns just the integer part.

    Now let’s take another example to understand a special case. If the string is alphanumeric, casting with (int) works differently.

    • If the string starts with digits followed by non-numeric characters, only the initial digits are considered.
    • If the string starts with non-numeric characters and the digits are in the middle, the csting operator returns “0”.

    Take a look at the following example −

    Open Compiler

    <?php
       $a = "10 Rs.";
       $b = (int)$a;
       var_dump($b);
    
       $a = "$100";
       $b = (int)$a;
       var_dump($b);
    ?>

    It will produce the following output −

    int(10)
    int(0)
    

    Casting to Float Type

    You can use either the (float) or (double) casting operator to explicitly convert a variable or expression to a float.

    Open Compiler

    <?php
       $a = 100;
       $b = (double)$a;
       var_dump($b);
    ?>

    It will produce the following output −

    float(100)
    

    A string containing any valid numeric representation may be cast to a float type by using a casting operator.

    Open Compiler

    <?php
       $a = "100";
       $b = (double)$a;
       var_dump($b);
    
       $a = "9.99";
       $b = (float)$a;
       var_dump($b);
    ?>

    Here, you will get the following output −

    float(100)
    float(9.99)
    

    The string gets converted to float even when it embeds a scientific notation of float. Take a look at the following example −

    Open Compiler

    <?php
       $a = "1.23E01";
       $b = (double)$a;
       var_dump($b);
       $a = "5.5E-5";
       $b = (float)$a;
       var_dump($b);
    ?>

    It will produce the following output −

    float(12.3)
    float(5.5E-5)
    

    All the non-numeric characters after the floating point numbers are ignored. Similarly, the string converts to “0” if it starts with any non-numeric character. See the following example −

    Open Compiler

    <?php
       $a = "295.95 only";
       $b = (double)$a;
       var_dump($b);
    
       $a = "$2.50";
       $b = (float)$a;
       var_dump($b);
    ?>

    It will produce the following output −

    float(295.95)
    float(0)
    

    Casting to String Type

    By using a casting operator, any expression evaluating to a floating-point or integer may be cast to a string type. Few examples are given below −

    Open Compiler

    <?php
       $a = 100;
       $b = (string)$a;
       var_dump($b);
    
       $x = 55.50;
       $y = (string)$x;
       var_dump($y);
    ?>

    You will get the following output −

    string(3) "100"
    string(4) "55.5"
    

    Casting to Bool Type

    Any non-zero number, either integer or float, is cast to true with (bool) operator. An expression evaluating to “0” returns false. A string is always cast to true.

    Take a look at the following example −

    Open Compiler

    <?php
       $a = 100;
       $b = (bool)$a;
    
       $x = 0;
       $y = (bool)$x;
    
       $m = "Hello";
       $n = (bool)$m;
    
       var_dump($b);
       var_dump($y);
       var_dump($n);
    ?>

    It will produce the following output −

    bool(true)
    bool(false)
    bool(true)
    

    Type Casting Functions

    PHP includes the following built-in functions for performing type casting −

    • intval()
    • floatval()
    • strval()

    Let’s discuss these built-in functions in detail.

    The intval() Function

    This function gets the integer value of a variable.

    intval(mixed$value,int$base=10):int

    The $base parameter is 10 by default, which means the value is converted to decimal number.

    • If the value is a float, the intval() function returns an integer, discarding the fractional part.
    • A string representation of a number returns a corresponding integer, discarding the fractional part, if any.
    • If the value is a string with a valid octal number and the base is 8, the intval() function returns a corresponding octal number.

    When the base is “0”, the conversion of value takes place on the basis of character prefix.

    • If the value starts with 0X or 0x, a hexadecimal number is returned.
    • If the value starts with 0B or 0b, a binary number is returned
    • If the value starts with 0, the function returns an octal number.

    The intval() function returns 1 for true, 0 for false Boolean values.

    Example

    The following example shows how the intval() function works −

    Open Compiler

    <?php
       echo intval(42). PHP_EOL;                     
       echo intval(4.2). PHP_EOL;                    
       echo intval('42') . PHP_EOL;                   
    
       echo intval(042) . PHP_EOL;         # 0ctal number 
       echo intval('042', 0) . PHP_EOL;    # 0ctal number
       echo intval('42', 8) . PHP_EOL;     # octal  
    
       echo intval(0x1A) . PHP_EOL;        # Hexadecimal              
       echo intval('0x1A', 16) . PHP_EOL;  # Hexadecimal           
       echo intval('0x1A', 0) . PHP_EOL;   # Hexadecimal         
    
       echo intval(false) . PHP_EOL;                  
       echo intval(true) . PHP_EOL; 
    ?>

    It will produce the following output −

    42
    4
    42
    34
    34
    34
    26
    26
    26
    0
    1
    

    The floatval() Function

    The floatval() function gets the float value of an expression.

    floatval(mixed$value):float

    The value may be any scalar variable. String with non-numeric characters returns “0”. A string with a numeric representation or with the starting substring with a numeric representation returns the corresponding number. The following example shows how the floatval() function works −

    Open Compiler

    <?php
       echo floatval(42). PHP_EOL;                     
       echo floatval(4.2). PHP_EOL;                    
       echo floatval('42') . PHP_EOL;                   
    
       echo floatval('99.90 Rs') . PHP_EOL;      
       echo floatval('$100.50') . PHP_EOL;      
       echo floatval('ABC123!@#') . PHP_EOL; 
    
       echo (true) . PHP_EOL; ;
       echo (false) . PHP_EOL; 
    ?>

    It will produce the following output −

    42
    4.2
    42
    99.9
    0
    0
    1
    

    The doubleval() function is an alias of floatval() function, and hence returns similar results.

    The strval() Function

    The strval() function gets the string value of a variable. This function performs no formatting on the returned value.

    strval(mixed$value):string

    The value that is being converted to a string may be any scalar type, null, or an object that implements the __toString() method. Take a look at the following example −

    Open Compiler

    <?php
       echo strval(42). PHP_EOL;                     
       echo strval(4.2). PHP_EOL;                    
       echo strval(4.2E5) . PHP_EOL;                   
    
       echo strval(NULL) . PHP_EOL;      
    
       echo (true) . PHP_EOL; 
       echo (false) . PHP_EOL; 
    ?>

    It will produce the following output −

    42
    4.2
    420000
    
    1
    

    The following example defines a class that implements the _toString() method.

    Open Compiler

    <?php
       class myclass {
    
      public function __toString() {
         return __CLASS__;
      }
    } echo strval(new myclass); ?>

    Here, you will get the following output −

    myclass
    
  • 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.

    Open Compiler

    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 age private and salary as protected by prefixing double and single underscores respectively.

    Open Compiler

    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.

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    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.

    Open Compiler

    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 −

    Open Compiler

    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
  • Data Types

    The term “data types” refers to the classification of data in distinct categories. PHP has a total of eight data types that we use to construct our variables −

    • Integers − Whole numbers, without a decimal point, like 4195.
    • Doubles − Floating-point numbers like 3.14159 or 49.1.
    • Booleans − Have only two possible values, either true or false.
    • NULL − Special type that only has one value: NULL.
    • Strings − Sequences of characters, like ‘PHP supports string operations.’
    • Arrays − Named and indexed collections of other values.
    • Objects − Instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
    • Resources − Special variables that hold references to resources external to PHP (such as database connections).

    The first five are simple types, and the next two (arrays and objects) are compound types. The compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.

    In this chapter, let’s discuss in detail about these built-in data types of PHP.

    Integer Data Type in PHP

    A whole number without a decimal point (like 4195) is of int type in PHP. Integer data types are the simplest type. They correspond to simple whole numbers, both positive and negative.

    • An int is a number of the set Z = {…, -2, -1, 0, 1, 2, …}.
    • An int can be represented in a decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation.

    To use octal notation, a number is preceded with “0o” or “0O”. To use hexadecimal notation, precede the number with “0x”. To use binary notation, precede the number with “0b”.

    Given below are some examples −

    • Decimal Integer − 201, 4195, -15
    • Octal Integer − 0010, 0O12, -0O21
    • Hexadecimal Integer − 0x10, -0x100
    • Binary Integer − 0b10101, -0b100

    Integers can be assigned to variables, or they can be used in expressions, like so −

    $int_var=12345;$another_int=-12345+12345;

    Double Data Type in PHP

    Double variables represent floating point numbers (also known as “floats”, “doubles”, or “real numbers”) that are the numbers with a fractional component. The fractional component follows after the integer component separated by the decimal symbol (.)

    Note − A double variable can be positive, negative, or zero.

    $var1=1.55$var2=-123.0

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Scientific Float Notation

    PHP also allows the use of scientific notation to represent a floating point number with more digits after the decimal point. The symbol “E” or “e” is used to separate the integer and fractional part.

    − 1.2e3,2.33e-4,7E-10,1.0E5

    By default, doubles print with the minimum number of decimal places needed. Take a look at the following example −

    Open Compiler

    <?php
       $many = 2.2888800;
       $many_2 = 2.2111200;
       $few = $many + $many_2;
    
       print("$many + $many_2 = $few");
    ?>

    It produces the following output −

    2.28888 + 2.21112 = 4.5
    

    Boolean Data Type in PHP

    The bool type only has only two values; it can either be True or False. The bool type is used to express a truth value.

    $bool1=true;$bool2=false;

    You can also use the integer values “1” and “0” to represent True and False Boolean values −

    $bool3=1;$bool4=0;

    Typically, the result of an operator which returns a bool value is passed on to a control structure such as if, while or do-while. For example,

    if(TRUE)print("This will always print.");elseprint("This will never print.");

    Interpreting Other Data Types as Booleans

    Here is a set of rules that you can use to interpret other data types as Booleans −

    • If the value is a number, then it is False only if the value is equal to zero, otherwise the value is True.
    • If the value is a string, it is False if the string is empty (has zero characters) or is the string “0”, and is True otherwise.
    • The values of type NULL are always False.
    • If the value is an array, it is False if it contains no other values; True otherwise. For an object, containing a value means having a member variable that has been assigned a value.
    • Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).

    Note − Don’t use double as Booleans.

    Each of the following variables has the truth value embedded in its name when it is used in a Boolean context.

    $true_num=3+0.14159;$true_str="Tried and true"$true_array[49]="An array element";$false_array=array();$false_null=NULL;$false_num=999-999;$false_str="";

    String Data Type in PHP

    A string is a sequence of characters, for example, ‘PHP supports string operations.’

    In PHP, a character is the same as a byte. It means PHP only supports a 256 character set, and hence does not offer native Unicode support.

    PHP supports single-quoted as well as double-quoted string formation. Both the following representations are valid in PHP −

    $string_1="This is a string in double quotes";$string_2='This is a somewhat longer, singly quoted string';

    Here are some more examples of string type −

    $string_39="This string has thirty-nine characters";$string_0="";// a string with zero characters

    Single-quoted strings are treated almost literally, whereas double-quoted strings replace variables with their values as well as specially interpreting certain character sequences.

    Open Compiler

    <?php
       $variable = "name";
       $literally = 'My $variable will not print!';
    
       print($literally);
       print "\n";
    
       $literally = "My $variable will print!";
       print($literally);
    ?>

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

    My $variable will not print!
    My name will print
    

    There are no artificial limits on string length. Within the bounds of available memory, you ought to be able to make arbitrarily long strings.

    Strings that are delimited by double quotes (as in “this”) are preprocessed in both the following two ways by PHP −

    • Certain character sequences beginning with backslash (\) are replaced with special characters.
    • Variable names (starting with $) are replaced with string representations of their values.

    The escape-sequence replacements are −

    • \n is replaced by the newline character
    • \r is replaced by the carriage-return character
    • \t is replaced by the tab character
    • \$ is replaced by the dollar sign itself ($)
    • \” is replaced by a single double-quote (“)
    • \\ is replaced by a single backslash (\)

    PHP also has Heredoc and Nowdoc representations of string data type.

    Heredoc Representation of String Data Type

    You can assign multiple lines to a single string variable using heredoc −

    <?php
       $channel =<<<_XML_
    
       <channel>
    
      &lt;title&gt;What's For Dinner&lt;/title&gt;
      &lt;link&gt;http://menu.example.com/ &lt;/link&gt;
      &lt;description&gt;Choose what to eat tonight.&lt;/description&gt;
    </channel> _XML_; echo <<< END
      This uses the "here document" syntax to output multiple lines with 
    variable interpolation. Note that the here document terminator must appear on a line with just a semicolon. no extra whitespace! END; print $channel; ?>

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

    This uses the "here document" syntax to output
    multiple lines with variable interpolation. Note
    that the here document terminator must appear on a
    line with just a semicolon. no extra whitespace!
    
    <channel>
       <title>What's For Dinner</title>
       <link>http://menu.example.com/ </link>
       <description>Choose what to eat tonight.</description>
    </channel>
    

    Nowdoc Representation of String Data Type

    All the rules for heredoc identifiers also apply to nowdoc identifiers. A nowdoc is specified just like a heredoc, but there is no parsing inside a nowdoc. You can use the nowdoc construct for embedding large blocks of text without having to use any escape characters.

    A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier is enclosed in single quotes, e.g. <<<‘EOT’. Nowdocs apply to single-quoted strings just the way heredocs apply to double-quoted strings.

    Take a look at the following example −

    Open Compiler

    <?php
       echo <<<'IDENTIFIER'
       As the cat cleared its throat with a refined "Meow",
       the squirrel chirped excitedly about its latest
       discovery of a hidden stash of peanut treasure!
       IDENTIFIER;
    ?>

    Run the code and check its output −

    As the cat cleared its throat with a refined "Meow",
    the squirrel chirped excitedly about its latest
    discovery of a hidden stash of peanut treasure!
    

    Null Data Type in PHP

    In PHP, null represents a special type that only has one value: NULL. Undefined and unset() variables will resolve to the value “null”.

    Programmers normally use the Null data type in PHP to initialize variables or to indicate that a value is missing.

    To give a variable the NULL value, simply assign it like this −

    $my_var=NULL;

    The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed −

    $my_var=null;

    A variable that has been assigned NULL has the following properties −

    • It evaluates to FALSE in a Boolean context.
    • It returns FALSE when tested with IsSet() function.

    Note − The data types of variables in PHP are determined at runtime based on the values that are assigned to them.

    Array Data Type in PHP

    An array in PHP is an ordered map, a key is associated with one or more values. A PHP array is defined using the array() function, or with the use of a short notation where the data is put in square brackets.

    Take a look at the following examples of associative arrays −

    Using the array() Function

    $arr=array("foo"=>"bar","bar"=>"foo",);

    Using the Short Notation

    $arr=["foo"=>"bar","bar"=>"foo",];

    An array in PHP can also be defined with the “key-value pair” syntax. It is called an indexed array.

    $arr=array("foo","bar","hello","world");

    In a multi-dimensional array, each element in the main array can also be an array. And, each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

    Note − In PHP, compound data types are used to store collections of data, including arrays and objects.

    Object Data Type in PHP

    An object type is an instance of a programmer-defined class, which can package up both other kinds of values and functions that are specific to the class.

    To create a new object, use the new statement to instantiate a class −

    classfoo{functionbar(){echo"Hello World.";}}$obj=newfoo;$obj->bar();

    Resource Data Type in PHP

    Resources are special variables that hold references to resources external to PHP (such as a file stream or database connections).

    Here is an example of file resource −

    $fp=fopen("foo.txt","w");

    Data belonging to any of the above types is stored in a variable. However, since PHP is a dynamically typed language, there is no need to specify the type of a variable, as this will be determined at runtime.

    Example: The gettype() Function

    The gettype() function is helpful to find out the type of data stored in a variable −

    Open Compiler

    <?php
       $x = 10;
       echo gettype($x) . "\n";
    
       $y = 10.55;
       echo gettype($y) . "\n";
    
       $z = [1,2,3,4,5];
       echo gettype($z);
    ?>

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

    integer
    double
    array
    
  • 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

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    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.

    Open Compiler

    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 −

    Open Compiler

    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.

    Open Compiler

    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.

    Open Compiler

    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.

    Open Compiler

    classStudent:def__init__(self,*args):iflen(args)==1:
    
         self.name = args&#91;0]eliflen(args)==2:
         self.name = args&#91;0]
         self.age = args&#91;1]eliflen(args)==3:
         self.name = args&#91;0]
         self.age = args&#91;1]
         self.gender = args&#91;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

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    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.

    Open Compiler

    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.

    Open Compiler

    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.