We can also overwrite our initial values by simply assigning new values to the attributes:
In [ 9 ]: c.a = 100
In [ 10 ]: c.a
Out[10]: 100
Python is quite flexible when it comes to the use of classes and objects. For example,
attributes of an object can be defined even after instantiation, as the following example
illustrates:
In [ 11 ]: c = ExampleOne()
In [ 12 ]: c.first_name = ‘Jason’
c.last_name = ‘Bourne’
c.movies = 4
In [ 13 ]: print c.first_name, c.last_name, c.movies
Out[13]: Jason Bourne 4
The class definition that follows introduces methods for classes. In this case, the class
ExampleThree is the same as ExampleTwo apart from the fact that there is a definition for a
custom method, addition:
In [ 14 ]: class ExampleThree(object):
def __init__(self, a, b):
self.a = a
self.b = b
def addition(self):
return self.a + self.b
Instantiation works as before. This time we use only integers for the attributes a and b:
In [ 15 ]: c = ExampleThree( 10 , 15 )
A call of the method addition then returns the sum of the two attribute values (as long as
it is defined, given the types of the attributes):
In [ 16 ]: c.addition()
Out[16]: 25
In [ 17 ]: c.a += 10
c.addition()
Out[17]: 35
One of the advantages of the object-oriented programming paradigm is reusability. As
pointed out, the class definitions for ExampleTwo and ExampleThree are only different with
respect to the custom method definition. Another way of defining the class ExampleThree
is therefore to use the class ExampleTwo and to inherit from this class the definition of the
special function init:
In [ 18 ]: class ExampleFour(ExampleTwo):
def addition(self):
return self.a + self.b
The behavior of instances of class ExampleFour is now exactly the same as that of
instances of class ExampleThree:
In [ 19 ]: c = ExampleFour( 10 , 15 )
In [ 20 ]: c.addition()
Out[20]: 25
Python allows for multiple inheritances. However, one should be careful with regard to
readability and maintainability, especially by others:
In [ 21 ]: class ExampleFive(ExampleFour):
def multiplication(self):
return self.a * self.b