UNIT-5 object oriented programming lecture

w6vsy4fmpy 38 views 35 slides Jul 31, 2024
Slide 1
Slide 1 of 35
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35

About This Presentation

Oops in python


Slide Content

RAISONI GROUP OF INSTITUTIONS Presentation On “Programming with Python” By Ms. H. C Kunwar Assistant Professor Department of Computer Engineering G. H. Raisoni Polytechnic, Nagpur. RAISONI GROUP OF INSTITUTIONS 1

RAISONI GROUP OF INSTITUTIONS 2 Department of Computer Engineering Unit 5 ( 12 Marks ) Object Oriented Programming in Python Lecture-1

RAISONI GROUP OF INSTITUTIONS 3 5.1 Creating Classes & Objects in Python Python Objects and Classes : Python is an object oriented programming language. Unlike procedure oriented programming, where the main emphasis is on functions, object oriented programming stresses on objects. An object is simply a collection of data (variables) and methods (functions) that act on those data. An object is also called an instance of a class and the process of creating this object is called instantiation . A class is a blueprint for that object. As many houses can be made from a house's blueprint, we can create many objects from a class. For Example : We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object .

RAISONI GROUP OF INSTITUTIONS 4 5.1 Creating Classes & Objects in Python Defining a Class in Python : Like function definitions begin with the def keyword in Python, class definitions begin with a class keyword . The first string inside the class is called docstring and has a brief description about the class. Although not mandatory, this is highly recommended. Here is a simple class definition . A class creates a new local namespace where all its attributes are defined. Attributes may be data or functions . There are also special attributes in it that begins with double underscores __. For example, __doc__ gives us the docstring of that class. As soon as we define a class, a new class object is created with the same name. This class object allows us to access the different attributes as well as to instantiate new objects of that class. class MyNewClass : '''This is a docstring . I have created a new class''' pass

RAISONI GROUP OF INSTITUTIONS 5 5.1 Creating Classes & Objects in Python Example : class Person: "This is a person class" age = 10 def greet(self): print('Hello') # Output: 10 print( Person.age ) # Output: <function Person.greet > print( Person.greet ) # Output: 'This is my second class' print( Person.__doc __) Output 10 <function Person.greet at 0x7fc78c6e8160> This is a person class

RAISONI GROUP OF INSTITUTIONS 6 5.1 Creating an Objects in Python Creating an Object in Python : We saw that the class object could be used to access different attributes. It can also be used to create new object instances (instantiation) of that class. The procedure to create an object is similar to a function call. >>> harry = Person() This will create a new object instance named harry. We can access the attributes of objects using the object name prefix. Attributes may be data or method. Methods of an object are corresponding functions of that class. This means to say, since Person.greet is a function object (attribute of class), Person.greet will be a method object.

RAISONI GROUP OF INSTITUTIONS 7 5.1 Creating Objects in Python Example : class Person: "This is a person class" age = 10 def greet(self): print('Hello') # create a new object of Person class harry = Person() # Output: <function Person.greet > print( Person.greet ) # Output: <bound method Person.greet of <__ main__.Person object>> print( harry.greet ) # Calling object's greet() method # Output: Hello harry.greet() Output : <function Person.greet at 0x7fd288e4e160> <bound method Person.greet of <__ main__.Person object at 0x7fd288e9fa30>> Hello

RAISONI GROUP OF INSTITUTIONS 8 5.1 Creating Objects in Python Explanation : You may have noticed the self parameter in function definition inside the class but we called the method simply as harry.greet() without any arguments. It still worked. This is because, whenever an object calls its method, the object itself is passed as the first argument. So, harry.greet() translates into Person.greet (harry). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method's object before the first argument. For these reasons, the first argument of the function in class must be the object itself. This is conventionally called self. It can be named otherwise but we highly recommend to follow the convention.

RAISONI GROUP OF INSTITUTIONS 9 5.1 Creating Objects in Python Example : class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc (self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc() Output : Hello my name is John Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.

RAISONI GROUP OF INSTITUTIONS 10 5.1 Creating Objects in Python The self Parameter : The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class: Example : Use the words mysillyobject and abc instead of self: class Person: def __init__( mysillyobject , name, age): mysillyobject.name = name mysillyobject.age = age def myfunc ( abc ): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc() Output : Hello my name is John

RAISONI GROUP OF INSTITUTIONS 11 Constructors in Python : Class functions that begin with double underscore __ are called special functions as they have special meaning. Of one particular interest is the __init__() function. This special function gets called whenever a new object of that class is instantiated. This type of function is also called constructors in Object Oriented Programming (OOP). We normally use it to initialize all the variables. class ComplexNumber : def __init__(self, r=0, i =0): self.real = r self.imag = i def get_data (self): print(f'{ self.real }+{ self.imag }j') 5.1 Creating Constructors in Python

RAISONI GROUP OF INSTITUTIONS 12 5.1 Creating Constructors in Python Output : 2+3j (5, 0, 10) Traceback (most recent call last): File "<string>", line 27, in <module> print(num1.attr) AttributeError : ' ComplexNumber ' object has no attribute ' attr '

RAISONI GROUP OF INSTITUTIONS 13 5.1 Deleting Attributes and Objects in Python Deleting Attributes and Objects : Any attribute of an object can be deleted anytime, using the del statement . >>> num1 = ComplexNumber (2,3) >>> del num1.imag >>> num1.get_data () Traceback (most recent call last): ... AttributeError : ' ComplexNumber ' object has no attribute ' imag ‘ >>> del ComplexNumber.get_data >>> num1.get_data() Traceback (most recent call last): ... AttributeError : ' ComplexNumber ' object has no attribute ' get_data '

RAISONI GROUP OF INSTITUTIONS 14 5.1 Creating Constructors in Python We can even delete the object itself, using the del statement. >>> c1 = ComplexNumber (1,3) >>> del c1 >>> c1 Traceback (most recent call last): ... NameError : name 'c1' is not defined Actually, it is more complicated than that. When we do c1 = ComplexNumber (1,3), a new instance object is created in memory and the name c1 binds with it. On the command del c1, this binding is removed and the name c1 is deleted from the corresponding namespace. The object however continues to exist in memory and if no other name is bound to it, it is later automatically destroyed. This automatic destruction of unreferenced objects in Python is also called garbage collection.

RAISONI GROUP OF INSTITUTIONS 15 5.2 Method Overloading in Python Method Overloading : Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading. Note: Python does not support method overloading. We may overload the methods but can only use the latest defined method. # Function to take multiple arguments def add( datatype , * args ): # if datatype is int # initialize answer as 0 if datatype ==' int ': answer = 0 # if datatype is str # initialize answer as '' if datatype ==' str ': answer ='' # Traverse through the arguments for x in args : # This will do addition if the # arguments are int. Or concatenation # if the arguments are str answer = answer + x print(answer) # Integer add(' int ', 5, 6) # String add(' str ', 'Hi ', 'Geeks') Output: Output : 11 Hi Geeks

RAISONI GROUP OF INSTITUTIONS 16 5.1 Method Overloading in Python ? Example : class Employee : def Hello_Emp ( self,e_name =None): if e_name is not None: print("Hello "+ e_name ) else: print("Hello ") emp1=Employee() emp1.Hello_Emp() emp1.Hello_Emp("Besant ") Output : Hello Hello Besant Example: class Area: def find_area ( self,a = None,b =None): if a!=None and b!=None: print("Area of Rectangle:",(a*b)) elif a!=None: print("Area of square:",(a*a)) else: print("Nothing to find") obj1=Area() obj1.find_area() obj1.find_area(10) obj1.find_area(10,20) Output: Nothing to find Area of a square: 100 Area of Rectangle: 200

RAISONI GROUP OF INSTITUTIONS 17 5.2 Method Overriding in Python ? Method Overriding : Method overriding is an example of run time polymorphism. In this, the specific implementation of the method that is already provided by the parent class is provided by the child class. It is used to change the behavior of existing methods and there is a need for at least two classes for method overriding. In method overriding, inheritance always required as it is done between parent class(superclass) and child class(child class) methods.

RAISONI GROUP OF INSTITUTIONS 18 5.2 Method Overriding in Python ? class A: def fun1(self): print('feature_1 of class A') def fun2(self): print('feature_2 of class A') class B(A): # Modified function that is # already exist in class A def fun1(self): print('Modified feature_1 of class A by class B') def fun3(self): print('feature_3 of class B') # Create instance obj = B() # Call the override function obj.fun1() Output: Modified version of feature_1 of class A by class B

RAISONI GROUP OF INSTITUTIONS 19 5.2 Method Overriding in Python ? #Example : Python Method Overriding class Employee: def message(self): print('This message is from Employee Class') class Department(Employee): def message(self): print('This Department class is inherited from Employee') emp = Employee() emp.message() print('------------') dept = Department() dept.message() Output :

RAISONI GROUP OF INSTITUTIONS 20 5.2 Method Overriding in Python ? Example : class Employee: def message(self): print('This message is from Employee Class') class Department(Employee): def message(self): print('This Department class is inherited from Employee') class Sales(Employee): def message(self): print('This Sales class is inherited from Employee') emp = Employee() emp.message() print ('------------') dept = Department() dept.message() print ('------------') sl = Sales() sl.message () Output :

RAISONI GROUP OF INSTITUTIONS 21 5.2 Method Overriding in Python ? Sr. No. Method Overloading Method Overriding 1 Method overloading is a compile time polymorphism Method overriding is a run time polymorphism. 2 It help to rise the readability of the program. While it is used to grant the specific implementation of the method which is already provided by its parent class or super class. 3 It is occur within the class. While it is performed in two classes with inheritance relationship. 4 Method overloading may or may not require inheritance. While method overriding always needs inheritance. 5 In this, methods must have same name and different signature. While in this, methods must have same name and same signature. 6 In method overloading, return type can or can not be same, but we must have to change the parameter. While in this, return type must be same or co-variant.

RAISONI GROUP OF INSTITUTIONS 22 5.3 Data Hiding in Python ? Data Hiding : Data hiding in Python is the method to prevent access to specific users in the application. Data hiding in Python is done by using a double underscore before (prefix) the attribute name. This makes the attribute private/ inaccessible and hides them from users . Data hiding ensures exclusive data access to class members and protects object integrity by preventing unintended or intended changes. Example : class MyClass : __ hiddenVar = 12 def add(self, increment): self.__ hiddenVar += increment print (self.__ hiddenVar ) myObject = MyClass () myObject.add (3) myObject.add (8) print ( myObject ._ MyClass __ hiddenVar ) Output 15 23 23

RAISONI GROUP OF INSTITUTIONS 23 5.3 Data Hiding in Python ? Data Hiding : Data hiding In Python, we use double underscore before the attributes name to make them inaccessible/private or to hide them. The following code shows how the variable __ hiddenVar is hidden. Example : class MyClass : __ hiddenVar = 0 def add(self, increment): self.__ hiddenVar += increment print (self.__ hiddenVar ) myObject = MyClass () myObject.add (3) myObject.add (8 ) print ( myObject .__ hiddenVar ) Output 3 Traceback (most recent call last): 11 File "C:/Users/TutorialsPoint1/~_1.py", line 12, in <module> print ( myObject .__ hiddenVar ) AttributeError : MyClass instance has no attribute '__ hiddenVar ' In the above program, we tried to access hidden variable outside the class using object and it threw an exception.

RAISONI GROUP OF INSTITUTIONS 24 5.4 Data Abstraction in Python ? Data Abstraction : Abstraction in Python is the process of hiding the real implementation of an application from the user and emphasizing only on usage of it. For example, consider you have bought a new electronic gadget. Syntax :

RAISONI GROUP OF INSTITUTIONS 25 5.4 Data Abstraction in Python ? Example : from abc import ABC, abstractmethod class Absclass (ABC): def print( self,x ): print("Passed value: ", x) @ abstractmethod def task(self): print("We are inside Absclass task") class test_class ( Absclass ): def task(self): print("We are inside test_class task") class example_class ( Absclass ): def task(self): print("We are inside example_class task") # object of test_class created test_obj = test_class () test_obj.task () test_obj.print (100) # object of example_class created example_obj = example_class () example_obj.task () example_obj.print (200) print (" test_obj is instance of Absclass ? ", isinstance ( test_obj , Absclass )) print(" example_obj is instance of Absclass ? ", isinstance ( example_obj , Absclass ))

RAISONI GROUP OF INSTITUTIONS 26 5.4 Data Abstraction in Python ? Output :

RAISONI GROUP OF INSTITUTIONS 27 5.5 Inheritance & composition classes in Python ? What is Inheritance (Is-A Relation ) : It is a concept of Object-Oriented Programming. Inheritance is a mechanism that allows us to inherit all the properties from another class. The class from which the properties and functionalities are utilized is called the parent class (also called as Base Class). The class which uses the properties from another class is called as Child Class (also known as Derived class). Inheritance is also called an Is-A Relation.

RAISONI GROUP OF INSTITUTIONS 28 5.5 Inheritance & composition classes in Python ? Syntax : # Parent class class Parent : # Constructor # Variables of Parent class # Methods ... ... # Child class inheriting Parent class class Child(Parent) : # constructor of child class # variables of child class # methods of child class

RAISONI GROUP OF INSTITUTIONS 29 5.5 Inheritance & composition classes in Python ? # parent class class Parent: # parent class method def m1(self): print('Parent Class Method called...') # child class inheriting parent class class Child(Parent): # child class constructor def __ init __(self): print('Child Class object created...') # child class method def m2(self): print('Child Class Method called...') # creating object of child class obj = Child() # calling parent class m1() method obj.m1() # calling child class m2() method obj.m2() Output : Child Class object created... Parent Class Method called... Child Class Method called...

RAISONI GROUP OF INSTITUTIONS 30 5.5 Inheritance & composition classes in Python ? What is Composition (Has-A Relation ) : It is one of the fundamental concepts of Object-Oriented Programming . In this we will describe a class that references to one or more objects of other classes as an Instance variable. Here , by using the class name or by creating the object we can access the members of one class inside another class. It enables creating complex types by combining objects of different classes . It means that a class Composite can contain an object of another class Component . This type of relationship is known as Has-A Relation.

RAISONI GROUP OF INSTITUTIONS 31 5.5 Inheritance & composition classes in Python ? Syntax : class A : # variables of class A # methods of class A ... ... class B : # by using " obj " we can access member's of class A. obj = A() # variables of class B # methods of class B ... ...

RAISONI GROUP OF INSTITUTIONS 32 5.5 Inheritance & composition classes in Python ? class Component: # composite class constructor def __ init __(self): print('Component class object created...') # composite class instance method def m1(self): print('Component class m1() method executed...') class Composite: # composite class constructor def __ init __(self): # creating object of component class self.obj1 = Component() print ('Composite class object also created...') # composite class instance method def m2(self): print ('Composite class m2() method executed...') # calling m1() method of component class self.obj1.m1() # creating object of composite class obj2 = Composite() # calling m2() method of composite class obj2.m2()

RAISONI GROUP OF INSTITUTIONS 33 5.6 Customization via inheritance specializing inherited methods in Python ? Customization via Inheritance specializing inherited methods: The tree-searching model of inheritance turns out to be a great way to specialize systems. Because inheritance finds names in subclasses before it checks superclasses, subclasses can replace default behavior by redefining the superclass's attributes. In fact, you can build entire systems as hierarchies of classes, which are extended by adding new external subclasses rather than changing existing logic in place. The idea of redefining inherited names leads to a variety of specialization techniques. For instance, subclasses may replace inherited attributes completely , provide attributes that a superclass expects to find, and extend superclass methods by calling back to the superclass from an overridden method.

RAISONI GROUP OF INSTITUTIONS 34 5.6 Customization via inheritance specializing inherited methods in Python ? Example- For specilaized inherited methods class A: "parent class" #parent class def display(self): print("This is base class ") class B(A): "Child class" #derived class def display(self): A.display (self) print("This is derived class") obj =B() #instance of child obj.display () #child calls overridden method Output: This is base class This is derived class

Thank you ! RAISONI GROUP OF INSTITUTIONS 35
Tags