Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER FIVE Classes.

Similar presentations


Presentation on theme: "CHAPTER FIVE Classes."— Presentation transcript:

1 CHAPTER FIVE Classes

2 Classes a class is like a template or blueprint for data and operations consists of a number of attributes that include variables and methods the variables are called data members, and methods are called member functions functions define the operations that can be applied to data members from classes, you create instances, also known as objects instances automatically get access to data members and methods.

3 Classes Why classes? an object is an instance of a class
object-oriented (OO)programming provides for reusable code (classes) OO programming focuses on the design of software that defines objects and how they interact it is always better to use old code than to start from scratch because existing code has already been used and tested it saves time in debugging a project

4 Classes Illustration of a class an example of a class can be car
An instance of car (BMW) will have the basic attributes (colour, make, model) it will also contain basic methods (accelerate, stop, turn) for any instance that you create there is no need to recreate these methods (code reuse)

5 Classes The class statement to create a class use the class statement
the class statement is an executable statement that is used for creating a class object and assigns it the name specified 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

6 Classes The class statement to create a class use the class statement
the class statement is an executable statement that is used for creating a class object syntax class class_name(parent-classes): suite (statements – class bofy) the class_name is the identifier (what the class is called) the parent-class is the one from the created class will copy data members and member functions

7 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) so demowind inherits from QWidget which inherits from QtGui if it is a non-derived class then class demowind:

8 Classes The __init__() method
is the first method to be executed after creation of an instance to perform initialisation 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 __init__() must not return a value

9 Classes The __init__() method Example :
class rect: # class called rect created def __init__(self): # init called to initialise variables of r 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 print ("Area of rectangle is ", r.rectarea()) Output: Area of rectangle is 40

10 Classes Passing arguments to _init__() method Example :
class rect: # class called rect created def __init__(self): # init called to initialise variables of r 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 print ("Area of rectangle is ", r.rectarea()) Output: Area of rectangle is 40

11 Classes Default values of the _init__() method Output:
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

12 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 in a class method, the class on which it is called is passed to it as the first argument. it can also be called directly through the class object without instantiating the class a class method is defined using decorator a decorator provides a convenient method to insert and modify code in functions or classes

13 Classes Class methods class book: # defining class price=100 # class variable initialised to def display(cls): # defining class method display print (cls.price) def show(self,x): self.price=x print (self.price) b=book() # instance of class called b c=book() # instance of class called c book.display() # class method called through book b.display() # class method called though b b.show(200) # instance method show called through b c.show(300) # instance method show called through c Output:

14 Classes Static methods
a static method is an ordinary function that is built decorator and that binds its result to a class attribute difference between a static method and a class method is that a static method has no cls parameter it does not use the self parameter the class method is automatically inherited by any child classes, whereas the static method is not also, the definition of a static method is immutable via inheritance a static method can be called on a class or on any instance of a class

15 Classes Static methods Example of a static method
class rect: # defining class rect @staticmethod def disp_message(): # defining static method disp _message l=50 # l initialised to 50 print ("Length is ", l) rect.disp_message() # static method called through rect r=rect() # instance method called r r.disp_message() # static method called through instance method r Output: Length is 50

16 Classes Output: Static method - The product count is: 2
Class methods vs static method class prod: count = 0 def __init__(self, name): self.name=name prod.count += def prodstatcount(): return def prodclasscount(cls): print('Class info: ', cls) print ('Class method - The product count is: ', cls.count) p1=prod('Camera') p2=prod('Cell') print('Static method - The product count is: ', prodct.prodstatcount()) p2.prodclasscount() Output: Static method - The product count is: 2 Class info: <class '__main__.prod uct'> Class method - The product count is: 2

17 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

18 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

19 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 Python uses a reference countering mechanism where each object has a reference count that indicates the number of references that exist for that object 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

20 Classes Garbage collection destructor.py class rect: n=0 def __init__(self,x,y): rect.n +=1 self.l=x self.b=y def __del__(self): rect.n -=1 class_name = self.__class__.__name__ print(class_name,' destroyed') def rectarea(self): print ('Area of rectangle is ', self.l * self.b) def noOfObjects(self): print ('Number of objects are: ', rect.n) r=rect(3,5) r.rectarea() s=rect(5,8) s.rectarea() r.noOfObjects() (cont) (cont) del r s.noOfObjects() del s Output: Area of rectangle is 15 Area of rectangle is 40 Number of objects are: 2 rect destroyed Number of objects are: 1

21 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

22 Classes Single inheritance
where one class is derived from another single class class B inherits class A, or class B is derived from class A A derived class has to identify the class from which it is derived example triangle class from is derived from the rect class then: class triangle(rect):

23 Classes Single inheritance – example

24 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 there are two keywords, public and private Public member — accessed from inside as well as outside of the class Private member — cannot be accessed from outside the body of the class a private member is preceded by a double underscore (__)

25 Classes Accessing public members - Example
defining and accessing public members the variables l and b are public members

26 Classes Accessing private members - Example
an identifier is defined starting with two underscores (__) but not ending with underscores, it is considered a private identifier of the class the variables l and b are private members

27 Classes Method overriding
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)

28 Classes Method overriding
the area() in class triangle overrides the one in class rect

29 Classes Accessing Methods of a Base Class from a Derived Class
One can access methods of the base class from the derived class by using a fully qualified name, by prefixing the class name to the method name as follows:

30 Classes Multilevel inheritance happens when a class inherits a class that is in turn inherited by some other class Example: class grandfather: ... class father(grandfather): class son(father): The son class inherits from the father class, which is a derived class of the grandfather class In this scenario, grandfather is the base class, father is an intermediate base class, and son is a derived class. Son inherits the properties of father directly and the properties of the grandfather class indirectly via the father class The son class can access the public members of the father class, which in turn can access the public members of the grandfather class

31 Classes Accessing Methods of a Base Class from a Derived Class
One can access methods of the base class from the derived class by using a fully qualified name, by prefixing the class name to the method name as follows:

32 Classes Two Classes Inheriting from the Same Base Class
this approach helps reduce the amount of code and effort

33 Classes Multiple inheritance
is when a class is derived from more than one base class class A { ... } class B class C(A,B) when you need to use the members of two or more classes (having no connection) via another class, you combine the features of all those classes by inheriting them

34 Multiple inheritance - example

35 Classes Two Base Classes Having a Method with the Same Name and
Signature if the two classes that are derived by a third class contain a method with the same signature, then the method of the first class will be executed

36 Classes Two Base Classes Having a Method with the Same Name and
Signature if the two classes that are derived by a third class contain a method with the same signature, then the method of the first class will be executed

37 Classes Operator Overloading
to overload a standard operator means that you apply arithmetic operators to a class instance to perform the desired operations you can add, subtract, multiply, and divide instances using the standard operators in the same way they are used with numbers for example, the __add__ method is used to add instances just as the plus operator (+) does

38 Classes Operator Overloading
The following program adds the instances r1 and r2 of the class rect through the + operator:

39 Classes Overloading the == operator
the following program explains how to overload the comparison operator (==) to see if the two instances have instance variables with the same value

40 Classes Polymorphism poly means many, and morph means change
through polymorphism, you can have a method with the same name in different classes to perform different tasks one can handle objects of different types in the same way to implement polymorphism, a number of classes or subclasses are defined that have method(s) with the same name these classes or subclasses are polymorphic one can access the polymorphic methods without knowing which class or subclass is invoked

41 Classes Polymorphism From the output, you observe that the
commission() method of each class calculates and displays the commission accordingly, hence implementing polymorphism

42 Notes


Download ppt "CHAPTER FIVE Classes."

Similar presentations


Ads by Google