WEB DEVELOPER SITE
PHP7
 

Python Object Oriented


Python is a object-oriented language.This chapter helps you become full developer using Python's object-oriented programming support.

Introduction of OOP Terminology

Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are class variables and instance variables and methods, accessed via dot notation.
Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.

  • Data member − A class variable or instance variable that holds data associated with a class and its objects.

  • Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.

  • Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class.

  • Inheritance − The transfer of the characteristics of a class to other classes that are derived from it.

  • Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.

  • Instantiation − The creation of an instance of a class.

  • Method − A special kind of function that is defined in a class definition.

  • Object − A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods.

  • Operator overloading − The assignment of more than one function to a particular operator.

    Creating Classes

    class statement creates a new class definition.


    class ClassName:
       'Optional class documentation string'
       class_suite
    
    • The class has a documentation string, which can be accessed via ClassName.__doc__.

    • The class_suite consists of all the component statements defining class members, data attributes and functions.

    Creating Instance Objects

    To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
    "This would create first object of Employee class"
    emp1 = Employee("Maria", 1000)
    "This would create second object of Employee class"
    emp2 = Employee("Ava", 1200)
    

    Accessing Attributes

    You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows −

    emp1.displayEmployee()
    emp2.displayEmployee()
    print "Total Employee %d" % Employee.empCount
    
    Now, putting all the concepts together
    #!/usr/bin/python
    
    class Employee:
       'Common base class for all employees'
       empCount = 0
    
       def __init__(self, name, salary):
          self.name = name
          self.salary = salary
          Employee.empCount += 1
       
       def displayCount(self):
         print "Total Employee %d" % Employee.empCount
    
       def displayEmployee(self):
          print "Name : ", self.name,  ", Salary: ", self.salary
    
    "This would create first object of Employee class"
    emp1 = Employee("Maria", 1000)
    "This would create second object of Employee class"
    emp2 = Employee("Ava", 1200)
    emp1.displayEmployee()
    emp2.displayEmployee()
    print "Total Employee %d" % Employee.empCount
    
    
    When the above code is executed, it produces the following result
    $python main.py
    Name :  Maria , Salary:  1000
    Name :  Ava , Salary:  1200
    Total Employee 2
    
    Run Example »

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

    emp1.age = 7  # Add an 'age' attribute.
    emp1.age = 8  # Modify 'age' attribute.
    del emp1.age  # Delete 'age' attribute.
    

    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.

    hasattr(emp1, 'age')    # Returns true if 'age' attribute exists
    getattr(emp1, 'age')    # Returns value of 'age' attribute
    setattr(emp1, 'age', 8) # Set attribute 'age' at 8
    delattr(empl, 'age')    # Delete attribute 'age'
    
    

    Built-In Class Attributes

    Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute −

    • __dict__ − Dictionary containing the class's namespace.

    • __doc__ − Class documentation string or none, if undefined.

    • __name__ − Class name.

    • __module__ − Module name in which the class is defined. This attribute is "__main__" in interactive mode.

    • __bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

      For the above class let us try to access all these attributes
      #!/usr/bin/python
      
      class Teacher:
         'Common base class for all Teachers'
         empCount = 0
      
         def __init__(self, name, salary):
            self.name = name
            self.salary = salary
            Teacher.empCount += 1
      
         def displayCount(self):
           print "Total Teacher %d" % Teacher.empCount
      
         def displayTeacher(self):
            print "Name : ", self.name,  ", Salary: ", self.salary
      
      print "Teacher.__doc__:", Teacher.__doc__
      print "Teacher.__name__:", Teacher.__name__
      print "Teacher.__module__:", Teacher.__module__
      print "Teacher.__bases__:", Teacher.__bases__
      print "Teacher.__dict__:", Teacher.__dict__
      
       
      
      When the above code is executed, it produces the following result
      $python main.py
      Teacher.__doc__: Common base class for all Teachers
      Teacher.__name__: Teacher
      Teacher.__module__: __main__
      Teacher.__bases__: ()
      Teacher.__dict__: {'__module__': '__main__', 'displayCount': , 'empCount': 0, 'displayTeacher': , '__doc__': 'Common base class for all Teachers', '__init__': }
      
      Run Example »

      Destroying Objects (Garbage Collection)

      The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection. The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.

      Example

      This __del__() destructor prints the class name of an instance that is about to be destroyed

      #!/usr/bin/python
      
      class Point:
          def __init__( self, x=0, y=0):
              self.x = x
              self.y = y
          def __del__(self):
              class_name = self.__class__.__name__
              print class_name, "destroyed"
      
      X = Point()
      Y = X
      Z = X
      print id(X), id(Y), id(Z) # prints the ids of the obejcts
      del X
      del Y
      del Z
      
      
      When the above code is executed, it produces following result
      $python main.py
      140158590223064 140158590223064 140158590223064
      Point destroyed
      
      
      Run Example »

      Class Inheritance

      Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name.

      Syntax

      Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name −

      class SubClassName (ParentClass1[, ParentClass2, ...]):
         'Optional class documentation string'
         class_suite

      Example

      #!/usr/bin/python
      
      class Parent:        # define parent class
         parentAttr = 100
         def __init__(self):
            print "Calling parent constructor"
      
         def parentMethod(self):
            print 'Calling parent method'
      
         def setAttr(self, attr):
            Parent.parentAttr = attr
      
         def getAttr(self):
            print "Parent attribute :", Parent.parentAttr
      
      class Child(Parent): # define child class
         def __init__(self):
            print "Calling child constructor"
      
         def childMethod(self):
            print 'Calling child method'
      
      c = Child()          # instance of child
      c.childMethod()      # child calls its method
      c.parentMethod()     # calls parent's method
      c.setAttr(100)       # again call parent's method
      c.getAttr()          # again call parent's method

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

      Calling child constructor
      Calling child method
      Calling parent method
      Parent attribute : 100
      
      Run Example »

      Overriding Methods

      You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass.
      #!/usr/bin/python
      
      class Parent:        # define parent class
         def myMethod(self):
            print 'Calling parent method'
      
      class Child(Parent): # define child class
         def myMethod(self):
            print 'Calling child method'
      
      c = Child()          # instance of child
      c.myMethod()         # child calls overridden method
      When the above code is executed, it produces the following result
      Calling child method
      
      Run Example »

      Overloading Operators

      You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation
      #!/usr/bin/python
      
      class Vector:
         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)
      
      x = Vector(6,4)
      y = Vector(-3,6)
      print x + y
      
      When the above code is executed, it produces the following result
      $python main.py
      Vector (3, 10)
      Run Example »