In [ 22 ]: c = ExampleFive( 10 , 15 )
In [ 23 ]: c.addition()
Out[23]: 25
In [ 24 ]: c.multiplication()
Out[24]: 150
For example, custom method definitions do not necessarily need to be included in the
class definition itself. They can be placed somewhere else, and as long as they are in the
global namespace, they can be used within a class definition. The following code
illustrates this approach:
In [ 25 ]: def multiplication(self):
return self.a * self.b
In [ 26 ]: class ExampleSix(ExampleFour):
multiplication = multiplication
And again, the instance of the class ExampleSix behaves exactly the same as the instance
of the earlier class ExampleFive:
In [ 27 ]: c = ExampleSix( 10 , 15 )
In [ 28 ]: c.addition()
Out[28]: 25
In [ 29 ]: c.multiplication()
Out[29]: 150
It might be helpful to have (class/object) private attributes. These are generally indicated
by one or two leading underscores, as the following class definition illustrates:
In [ 30 ]: class ExampleSeven(object):
def __init__(self, a, b):
self.a = a
self.b = b
self.__sum = a + b
multiplication = multiplication
def addition(self):
return self.__sum
The behavior is the same as before when it comes to a call of the method addition:
In [ 31 ]: c = ExampleSeven( 10 , 15 )
In [ 32 ]: c.addition()
Out[32]: 25
Here, you cannot directly access the private attribute sum. However, via the following
syntax, it is still possible:
In [ 33 ]: c._ExampleSeven__sum
Out[33]: 25
As the class ExampleSeven is defined, one must be careful with the inner workings. For
example, a change of an attribute value does not change the result of the addition method
call:
In [ 34 ]: c.a += 10
c.a
Out[34]: 20
In [ 35 ]: c.addition()
Out[35]: 25
This, of course, is due to the fact that the private attribute is not updated:
In [ 36 ]: c._ExampleSeven__sum
Out[36]: 25