Python Class and Objects

Programming languages that allow the programmer to define new classes of objects are called object-oriented languages. These languages also support a style of programming called object-oriented programming. Python classes provide all the standard features of Object Oriented Programming. the class inheritance mechanism facilitate you to define multiple base classes, any methods of its base class(s) can be overridden by derived class, and a method can call the method of a base class with the same name.

Basic OOP Terminology in Python

Before proceeding to example the user should be acquainted with Basic OOP Terminology

Python Object

An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. In pure OOP terms an object is an instance of a class.

Python Class

A Python class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.
The simplest form of class definition looks like this:
 class <class name >(<parent class name>):
    <method definition-1>
    <method definition-n>
According to python docs
Class definitions, like function definitions. In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful. When a class definition is entered, a new name-space is created, and used as the local scope - thus, all assignments to local variables go into this new name-space. In particular, function definitions bind the name of the new function here. The class definition syntax has two parts: a class header and a set of method definitions that follow the class header. The class header consists of the class name and the parent class name. The class name is a Python identifier.

Method Definitions

methods are a bit like functions. All of the method definitions are indented below the class header.


We must include this argument in the parameter list of a method, each method definition must include a first parameter named self, whether method is expecting argument or not. When an object calls a method, the interpreter binds the parameter self to that object so that the method's code can refer to the object by name. The code for method can then use self to access that particular object.

Python Class variable

Python Class variables are defined within a class but not in class's methods. Class variable is shared by all instances(object) of a class.

Creating Python class

Example 1 Start from very simple example
class student:
   def display(self, name ):
      print "your name is ", name
st1 = student()
st2 = student()
Python class example
Python class example
in above example a class named student has been created. A function named display is defined. display function contain two argument self and name. Two objects st1 and st2 have been created
Syntax of object creation
st1 = student()
You call the class using class name and call the function with arguments
Let us discuss our next example
class student:
   number =40
   def dis(self, name ):
      print name
      print number
st1 = student()
Python class variable access
Python class example 2
The above example shows that number =40, while executing, it is giving error, number is a class variable whose value would be shared among all instances of a this class. This can be accessed as student.number from inside the class or outside the class. Method inside the class can access the class variables by using self.

Consider another example with pictorial diagram.
Python Showing local and class variable
Showing local and class variable
Click to view code
Lots of sketching is there, Now you can understand the meaning of self to access class variable from method dis(). I used self because the interpreter binds the parameter self to that object (means class, object is the instance of class). The code binds the parameter self in the method dis() to the student class object referenced by the variable st1. The code for dis() can then use self to access that particular object's number. Otherwise, methods behave just like functions.

Below diagram is showing the graphical representation.
Python self bind the method with the object
self bind the method with the object

Let us discuss a comparison between, accessing class variable using self and accessing class variable using class name.
Python class comparsion self and class access
Python class comparsion self and class access
Click to view code
Click to view code
You can see a clear difference from above figure, self.number is just accessing the variable. But student.number can change the class variable because class variable number and class.number inside the method are same.

Python __init__ Method

In Object oriented programming, you have heard about constructor. The __init__ must begin and end with two consecutive underscores. Here __init__ works as class's constructor, because it is run automatically when a user instantiates the class. Let us discuss with example
Python class __init__()  initalize one by one
__init__() initalize one by one
Click to view code
In above example, empcount value is increasing. The object emp1 called the method inf() after initilization of __init__().

Python Class Inheritance

Inheritance h allows you to base a new class on an existing one. By doing so, the new child class automatically gets all of the methods and attributes of the existing parent class. In this way you can say the child class inherits the attributes of its parent class.
class DerivedClassName(BaseClassName):
    .    .
Let us discuss a example
Python Class Inheritance
Python Class Inheritance
Click to view code
The above example shows simple example of inheritance. The child class inherit the properties of parent class, that's why object of child class can access the method of parent class.

Python Overriding Methods

You can also override your parent class methods. By doing so, you can add special or different functionality in your subclass.
Let us discuss next example.
Python method  overriding
Python method overriding
Click to view code
In this example object c of child class call the method sum() but method sum() of parent class is overridden by child class

Python Operator Overloading

Python operators work for built-in classes. But same operator behaves differently with different types. For example add + use to add two integer and float. When it comes to string + operator concatenate two strings. This feature in Python, that allows same operator to have different meaning according to the context is called operator overloading.
For example consider of adding the (x,y) coordinates.
Python class Operator overloading
Python Operator overloading
Click to view code
You see add + is not adding coordinates, giving error.
The operator module exports a set of functions implemented in C corresponding to the intrinsic operators of Python. For example, operator.add(x, y) or operator.__add__(a, b) is equivalent to the expression x+y. The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience.
Ok, now back to operator overloading. Now we are going to do + operator overloading.
Python class comparison or equal to operator
comparison or equal to operator
The above program basically executed in 4 steps.
Step 1 and step 2 : Object p1 and p2 initialize the constructor __init__ with arguments.
Step 3 : When you do print p1+ p2
in __add__(self,other) method, we have added coordinates x1 with coordinates x2 and coordinates y1 with coordinates y2.
Step 4 : Printing the coordinates.

Operator Overloading Special Functions in Python
Operator Expression Internally
Addition p1 + p2 p1.__add__(p2)
Subtraction p1 - p2 p1.__sub__(p2)
Multiplication p1 * p2 p1.__mul__(p2)
Power p1 ** p2 p1.__pow__(p2)
Division p1 / p2 p1.__truediv__(p2)
Floor Division p1 // p2 p1.__floordiv__(p2)
Remainder (modulo) p1 % p2 p1.__mod__(p2)
Bitwise Left Shift p1 << p2 p1.__lshift__(p2)
Bitwise Right Shift p1 >> p2 p1.__rshift__(p2)
Bitwise AND p1 & p2 p1.__and__(p2)
Bitwise OR p1 | p2 p1.__or__(p2)
Bitwise XOR p1 ^ p2 p1.__xor__(p2)
Bitwise NOT ~p1 p1.__invert__()

Overloading Comparison Operators in Python
We can overload comparison operators as well. Suppose, we wanted to implement the less than or equal to symbol .
Python Operator overloading
Python Operator overloading
Click to view code
The < = symbol in our Vector class. Let us compare the magnitude of these points from the origin and return the result for this purpose.

Comparison Operator Overloading in Python.
Operator Expression Internally
Less than p1 < p2 p1.__lt__(p2)
Less than or equal to p1 <= p2 p1.__le__(p2)

Equal to

p1 == p2 p1.__eq__(p2)
Not equal to p1 != p2 p1.__ne__(p2)
Greater than p1 > p2 p1.__gt__(p2)
Greater than or equal to p1 >= p2 p1.__ge__(p2)

Python Private variable

In Python there are private attribute. Private variable begin with an underscore. Private attributes will not be directly visible to outsiders.
Let us discuss the example.
Python class Accessing private variable
Accessing private variable
Click to view code
Out side the class if you are accessing the private attibute, it will give error if you want to access the private attributes of class do as shown in next example
Python Accessing private variable
Python Accessing private variable
Click to view code
Use syntax object._class-name__private-attribute

Python Private methods

Python doesn't have real private methods, so one underline in the beginning of a method or attribute means you shouldn't access this method, because it's not part of the API. It's very common when using properties:
Let us discuss the example.
Python private varible
accessing private methods
Click to view code
To access private method you have to do same as we have done for access the private variable. a.__info() gives the error while accessing the private method.