Object Oriented

Special Method

Python

 

Constructor

Python 2.7
class Person: 
  
    def __init__(self, name, age):
        self.name = name
        self.age = age

Classes that have a Constructor method call this method on each newly-created object.

This method is suitable for any initialization that the object may need before it is used.

Here you can pass name and age when instantiating a Person object.

person1 = Person("Sam", 25)
 

Destructor

Python 2.7
class Person:
  
    def __del__(self):
        print("__del__ method called")

The __del__ method will be called as soon as there are no other references to a particular object.

This is a good place to close databases, files, ... connections.

 

Getter

Python 2.7
class Person:
  
    @property
    def fullname(self):
        return self.fname + ' ' + self.lname

You can define Getters using @property decorator.

If a getter method is defined, it is called whenever its name is tried to be read on an object using . operator, similar to reading a value of a property.

person1 = Person()
person1.fname = 'Sam'
person1.lname = 'Winchester'

fullname = person1.fullname  # Sam Winchester

This is a good way to expose private properties.

 

Setter

Python 2.7
class Person(object):

    @property
    def fullname(self):
        return self.fname + ' ' + self.lname

    @fullname.setter
    def fullname(self, value):
        names = value.split(' ')
        self.fname = names[0]
        self.lname = names[1]

You can define Setters using decorators.

If a setter method is defined, it is called whenever its name is tried to be set on an object using . operator, similar to setting a value for a property.

person1 = Person();
person1.fullname = "Sam Winchester";

firstname = person1.fname;  # Sam
lastname = person1.lname;   # Winchester

In Python2 in order setters to work, your class should inherit from object.

This is a good way to expose private properties.

 

toString

Python 2.7
class Person:
  
  def __str__(self):
    return self.name + " is " + str(self.age)
  
  def __repr__(self):
    return "name: " + self.name + ", age: " + str(self.age)

There are 2 special methods for creating a string representation of an object:

  • __str__ method is usually used to represent a readable string for an object.
  • __repr__ method is used mostly for debugging purposes.
person1 = Person()
person1.name = 'Sam'
person1.age = 25

str1 = str(person1)       # Sam is 25
str2 = repr(person1)      # name: Sam, age: 25
print(person1)            # Sam is 25
 

Clone

Python 2.7
import copy

class Person:
  
  def __init__(self, name, scores):
    self.name = name
    self.scores = scores

  def __copy__(self):
    return Person(self.name, self.scores)

  def __deepcopy__(self, memo):
    scores = copy.deepcopy(self.scores)
    return Person(self.name, scores)

There are 2 types of cloning:

  • Shallow Clone
  • Deep Clone

The __copy__ and __deepcopy__ methods are for these clonings.

person1 = Person('Sam', [[1],[1],[1]])
person2 = copy.copy(person1)
person3 = copy.deepcopy(person1)

person1.name = 'Joe'
person1.scores[0] = [5]

name1 = person1.name       # Joe
name2 = person2.name       # Sam
name3 = person3.name       # Sam
scores1 = person1.scores   # [[5], [1], [1]]
scores2 = person2.scores   # [[5], [1], [1]]
scores3 = person3.scores   # [[1], [1], [1]]
 

__len__

Python 2.7
class Person:
  
  def __len__(self):
    return 46

The __len__ method is called whenever the object is passed to the len function.

person1 = Person()
length = len(person1)
 

__getitem__

Python 2.7
class Person:
  
  def __init__(self): 
    self.scores = [10, 21, 7, 14, 9]
  
  def __getitem__(self, pos):
    return self.scores[pos]

The __getitem__ method lets you use the bracket [] operator on an object.

person1 = Person()
score1 = person1[0]       # 10
scores1 = person1[1:3]    # [21, 7]
 

__call__

Python 2.7
class Person:
  
  def __call__(self, x):
    print("Person triggered with " + str(x))

__call__ method is called when a script tries to call an object as a function.

person1 = Person()
person1(12)   # Person triggered with 12
 

Operator Overloading

Python 2.7
class Person:
  
  def __init__(self, salary): 
    self.salary = salary
  
  def __add__(self, other):
    return Person(self.salary + other.salary)

You can OverLoad operators like +, *, ... in your Class definitions.

person1 = Person(110000)
person2 = Person(70000)
person3 = person1 + person2

salary1 = person3.salary  # 180000

This will help you to write more readable code.

This is a list of operators and their methods to overload:

OperatorMethod
+aa.__pos__()
-aa.__neg__()
a + ba.__add__(b)
a - ba.__sub__(b)
a * ba.__mul__(b)
a ** ba.__pow__(b)
a / ba.__truediv__(b)
a // ba.__floordiv__(b)
a % ba.__mod__(b)
a << ba.__lshift__(b)
a >> ba.__rshift__(b)
a & ba.__and__(b)
a | ba.__or__(b)
a ^ ba.__xor__(b)
~aa.__invert__()
a < b a.__lt__(b)
a <= ba.__le__(b)
a == ba.__eq__(b)
a != ba.__ne__(b)
a > b a.__gt__(b)
a >= ba.__ge__(b)