Classes and OOP in Python – Part 2

Objects coded with classes intercept and respond to operations that work on built-in types: addition, slicing, printing, qualification, and so on. This is called operator overloading.

We will start with the example from “Classes and OOP in Python – Part 1”:

class MainClass:
	def setdata(self, value):
		self.data = value
	def display(self):
		print(self.data)

class ChildOneClass(MainClass):
	def display(self):
		print('Current value = "%s"' % self.data)

Now, we are going to create a third class which will be a subclass of ChildOneClass.

class GrandChildClass(ChildOneClass):
	def __init__(self, value):
		self.data = value
	def __add__(self, other):
		return GrandChildClass(self.data + other)
	def __str__(self):
		return '[GrandChildClass: %s]' % self.data
	def mul(self, other):
		self.data *= other

The newly created GrandChildClass implements three specially named attributes that Python will call automatically:

  • __init__ – it is run when a new instance object is created: self is the new GrandChildClass object (Not to be confused with the __init__.py files in module packages!).
  • __add__ – it is run when a GrandChildClass instance appears in a + expression.
  • __str__ – it is run when an object is printed
  • .

At the end, the new subclass defines a normally named method called mul, which changes the instance object in place.

Let’s do something with this class to see how things work:

A = GrandChildClass('abc') # __init__ is called
A.display() # inherit method called
print(A) # __str__ returns display string

B = A + 'def' # __add__ makes a new instance
B.display() # B has all GrandChildClass methods
print(B) # __str__ returns display string

A.mul(5) # mul changes instance in place
print(A)

Run the code in the terminal and you will get something like below (without the comments):

ddn_ro@Linux:~/Desktop$ python3 a.py
Current value = "abc" # inherit method called
[GrandChildClass: abc] # inherit method called

Current value = "abcdef" # B has all GrandChildClass methods
[GrandChildClass: abcdef] # __str__ returns display string

[GrandChildClass: abcabcabcabcabc] # mul changes instance in place

Our new class GrandChildClass inherits the display method from the ChildOneClass. The argument 'abc' is passed to the value argument in the __init__ constructor and assigned to self.data there. The current value becomes 'abc'.

Since there is a value the GrandChildClass objects can now show up in + expressions and print calls.

The __add__ says that when the self.data (which is A) is added to other (which is 'def') create a new instance of the GrandChildClass (which is B).

For print, Python passes the object being printed to self in __str__.

Leave a Reply