Chapter Five: Classes
Chapter Five: Classes
Chapter Five: Classes
Classes
Classes
• a class is like a template or blueprint for data and operations
• the variables are called data members, and methods are called member
functions
• it is always better to use old code than to start from scratch because
existing code has already been used and tested
• An instance of car (BMW) will have the basic attributes (colour, make,
model)
• for any instance that you create there is no need to recreate these
methods (code reuse)
Classes
The class statement
• can create an independent class or one that inherits from other classes
(derived class or sub-class)
• a derived class can inherit the attributes of the parent and can add its own
Classes
The class statement
• the parent-class is the one from the created class will copy data
members and member functions
Classes
The class statement – defining a class
• creating a class called demowind
class demowind(QtGui.QWidget):
• it will inherit from another class (QtGui) and from a specific class
(QWidget)
• first argument of every class method is a reference to the current instance of the
class
• the first argument is called self and refers to the newly created instance
• in other class methods, it refers to the instance whose method was called
• when defining __init__, the ancestor’s __init__ method must be called explicitly
if it exists
• default values can be specified for the parameters of the _init__() method
• if the value of any parameter is not supplied when initializing an instance, its default value is used :
class rect: # class called rect created
def __init__(self, x =8, y = 5): # default parameters
self.l = 8 #variable of instance r created and initialised
self.b = 5 #variable of instance r created and initialised
def rectarea(self):
return self.l * self.b
r=rect() # instance of rect class is created called r
S=rect(10,20) # instance of rect class is created called s
print ("Area of rectangle is ", r.rectarea())
print ("Area of rectangle is ", s.rectarea())
Output:
Area of rectangle is 40
Area of rectangle is 200
Classes
Class methods
• a class method has no self argument and receives a class as its first
argument
• the argument to the class method is called cls
Output:
Length is 50
Length is 50
Classes
Class methods vs static method Output:
class prod:
count = 0 • Static
def __init__(self, name): method - The
self.name=name product
prod.count += 1 count is: 2
@staticmethod
def prodstatcount():
• Class info:
return prod.count <class
@classmethod '__main__.pr
def prodclasscount(cls): oduct'>
print('Class info: ', cls)
print ('Class method - The product count is: ', cls.count)
• Class method
p1=prod('Camera')
- The
p2=prod('Cell') product
print('Static method - The product count is: ', count is: 2
prodct.prodstatcount())
p2.prodclasscount()
Classes
Assigning one instance to another
• Python provides a facility to assign one instance to another
• assigning an instance to another results in creation of a new instance if it
doesn’t exist
For example,
• assuming inst1 and inst2 are instances of some class, then the following
• statement:
• inst1=inst2
• will create the instance inst1 if it doesn’t exist, and all the instance
variables of inst1 will be initialized to values equal to those in instance
variables of inst2
Classes
Assigning one instance to another
assignobj.py
class rect:
def __init__(self, x,y):
self.l = x
self.b = y
def rectarea(self):
return self.l * self.b
r=rect(5,8)
s=r
print ("Area of rectangle is ", r.rectarea())
print ("Area of rectangle is ", s.rectarea())
Output:
Area of rectangle is 40
Area of rectangle is 40
Classes
Garbage collection
• is a procedure of freeing up the memory that is used by the variables or
instances that are no longer required
• memory that is used by the instances is usually freed up automatically when the
variables assigned to them go out of scope
• memory leaks are thus rare in Python
• the reference count increases for each reference added to the object and is
decreased by removing the reference to that object
• when the refer count reaches zero, the object is garbage collected
Classes
Garbage collection
destructor.py
(cont)
class rect: del r
n=0
def __init__(self,x,y): s.noOfObjects()
rect.n +=1
self.l=x del s
self.b=y
def __del__(self):
rect.n -=1 Output:
class_name = self.__class__.__name__
print(class_name,' destroyed') Area of rectangle is 15
def rectarea(self):
print ('Area of rectangle is ', self.l * self.b) Area of rectangle is 40
def noOfObjects(self):
print ('Number of objects are: ', rect.n)
Number of objects are: 2
r=rect(3,5) rect destroyed
r.rectarea()
s=rect(5,8) Number of objects are: 1
s.rectarea()
r.noOfObjects() (cont) rect destroyed
Classes
Inheritance
• is a technique of copying the data members and member functions of an
existing class into another class
• instead of beginning from scratch, an existing class can be inherited, and
additional data members and member functions can be defined
• the class that is being inherited is called the base class or the super class,
and the inheriting class is called the derived class or sub-class
• the sub-class inherits all the properties of the base class and hence results
in saving time and effort
• the three types of inheritance are:
• Single inheritance
• Multilevel inheritance
• Multiple inheritance
Classes
Single inheritance
• where one class is derived from another single class
class triangle(rect):
Classes
Single inheritance – example
Classes
Access control specifiers
• define the visibility of the members of the class
• all the members of the class are assigned a boundary in which they can be
accessed using these control specifiers
• an identifier is defined starting with two underscores (__) but not ending
with underscores, it is considered a private identifier of the class
• if in a derived class you have a member function with the same signature
as that of the base class, then you say that the member function of the
derived class is overriding the member function of the base class
• if the member function is invoked by the instance of the derived class, the
member function of the derived class will be executed (and not the member
function of the base class)
Classes
Method overriding
• through polymorphism, you can have a method with the same name in different
classes to perform different tasks
• one can access the polymorphic methods without knowing which class or subclass is
invoked
Classes
Polymorphism
From the output, you
observe that the
commission() method
of each class calculates
and displays the commission
accordingly, hence
implementing
polymorphism
Notes