Python Object Oriented


Contents

Python is known as an object-oriented language. Its open-source and high-level coding have enabled programmers to create and use classes and objects effortlessly. This chapter assists you to become proficient in utilizing Python's object-oriented programming support.

However, we are introducing small details about Object-Oriented Programming (OOP) −

Overview of OOP Terminology

  • Class – It is a user-defined sample for an object explaining a set of attributes. Also, OOP qualifies any object of the class. The characteristics are data members (case variables and class variables) and accessed via dot notation and methods.
  • Class variable − A variable is shared by entire cases of a class. Class variables are described inside a class however outside some of the class's techniques. Class variables are never utilized as regularly as example variables are.
  • Data member − A class variable or instance variable has always holds data connected with a class via its objects.
  • Function overloading − the service of over one performance to an exacting purpose. The operation executed varies depending upon the types of objects or arguments incorporated in it.
  • Instance variable − A variable, which has been defined in internal method may belongs to the actual instance of a class.
  • Inheritance – The classes or different classes that are derived are the transferred objects of the classes.
  • Instance− An individual object of a explicit class. An object obj that indicates to a class Circle, is expected to be an instance of the class Circle.
  • Instantiation – The term is used for an instance of a class creation.
  • Method – This means that a particular kind of function is defined in a class description.
  • Object − A sole example of a data design and structure specified by its class. An object contains mutual methods and data members (instance variables and class variables).
  • Operator overloading − The task of over one function to a meticulous operator.

Creating Classes

The class statement develops a new class of account. The name of the class right away adhere the keyword class followed by a colon as follows:

class ClassName:
   'Optional class documentation string'
   class_suite
  • The class has a documentation string, which can be accessed via ClassName.__doc__.
  • The class_suite comprise of entire component statements describing data attributes, class members, and functions.

Example

Following is the example of a simple Python class:

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
  • The variable empCount is a class variable. The value has been shared amid entire instances and classes. This could be accessed as Employee.empCount within the class or outside.
  • The first method __init__() is a particular method known to be class constructor or initialization method. This is the nomenclature provided by Python while the users create a new instance of such class.
  • Mostly, users prefer to declare other class methods assuming normal functions with the exception. Which means, they first argument to every process is self. Python adjoins the self argument to the list; however, users never demand to incorporate it when it call the methods.

Creating Instance Objects

To form instances of a class, users need to call the class name and pass __init__ method accepts.

"This would create first object of Employee class"
emp1 = Employee("Mack", 2000)
"This would create second object of Employee class"
emp2 = Employee("Sunni", 5000)

Accessing Attributes

Users access the object's attributes though the dot operator with object utilization. Class variable is acquired through 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("Mack", 2000)
"This would create second object of Employee class"
emp2 = Employee("Sunni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

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

Name :  Mack ,Salary:  2000
Name :  Sunni ,Salary:  5000
Total Employee 2

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.

Rather than utilizing the normal statements to right of entry attributes, users can use these 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 rolls out the provided built-in attributes. These attributes can be accessed through dot operator similar to 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 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

print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__

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

Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2, 
'displayEmployee': <function displayEmployee at 0xb7c8441c>, 
'__doc__': 'Common base class for all employees', 
'__init__': <function __init__ at 0xb7c846bc>}

Destroying Objects (Garbage Collection)

  • Python deletes not required objects mechanically to gratis the memory room. The procedure that the programming language ~ Python used periodically regains blocks of memory that no longer used as the termed Garbage Collection.
  • Python's garbage collector executes throughout program execution and is activated when an object's orientation count reaches zero. An object's position count modifies as the number of assumed names that point to it modifications.
  • An object's reference adding up improves when it is allocated a new name or put in a container. The object's reference calculating decreases while it is deleted with del, its allusion is relocated, or its reference goes out of range. While an object's position count reaches zero, Python gathers it mechanically.

You usually will never become aware of whilst the garbage collector wipes out an orphaned instance and retrieves its space. Excluding a class can apply the special method __del__(), called a destructor, that is incorporate when the example is about to be destroyed. This technique is used to onslaught any non-memory reserves applied by an instance.

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"

pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3

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

#!/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"

pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3

Note − preferably, users ought to describe the classes in different file. Users may import these files in main program file utilizing the command import statement.

Class Inheritance

Instead of beginning from scrape, users could create a class by deriving inheritance from a pre-existed class by Tuple the component class in parentheses. after the new class name. The child class inherits the attributes of its parent class. Users can employ those attributes if they have defined in the child class. Keep in mind, a child class can supersede data members and methods while inheriting from the parent.

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(200)       # 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 : 200

Similar way, you can drive a class from multiple parent classes as follows:

class A:        # define your class A
.....

class B:         # define your class B
.....

class C(A, B):   # subclass of A and B
.....

You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.

  • The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.
  • The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class

Overriding Methods

Users could always take priority over the parent class techniques. One of the reasons for superseding parent's methodology is preference of special or different functionality in subclass.

Example

#!/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

Base Overloading Methods

Following table lists some generic functionality that you can override in your own classes

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 )

Evaluable string representation

Sample Call : repr(obj)

4

__str__( self )

Printable string representation

Sample Call : str(obj)

5

__cmp__ ( self, x )

Object comparison

Sample Call : cmp(obj, x)

Overloading Operators

Presume that users have developed a Vector class to depict two-dimensional vectors. As a result, users apply the plus operator to put in I the class. However, the programming language notifies users about it.

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

#!/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)

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)

Data Hiding

An object's attributes perhaps stay noticeable outside the class definition. Users are required to name attributes providing a double underscore prefix. Mostly, these attributes are not directly observable to outsiders.

Example

#!/usr/bin/python

class JustCounter:
   __secretCount = 0
  
   def count(self):
      self.__secretCount += 1
      print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount

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

1
2
2

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.



Navigation
Tutorial
Tutorial
Tutorial