SlideShare a Scribd company logo
Python Programming
UNIT-3
Object Oriented Programming
 Python is a multi-paradigm programming language. It
supports different programming approaches.
 One of the popular approaches to solve a programming
problem is by creating objects. This is known as Object-
Oriented Programming (OOP).
 An object has two characteristics:
 attributes
 behavior
Let's take an example:
 A parrot is an object, as it has the following properties:
 name, age, color as attributes
 singing, dancing as behavior
 The concept of OOP in Python focuses on creating
reusable code. This concept is also known as DRY
(Don't Repeat Yourself).
Object
 An object (instance) is an instantiation of a class. When
class is defined, only the description for the object is
defined. Therefore, no memory or storage is allocated.
The example for object of parrot class can be:
 obj = Parrot()
 Here, obj is an object of class Parrot.
Class
 In Python, the concept of OOP follows some basic principles:
 A class is a blueprint for the object.
 We can think of class as a sketch of a parrot with labels. It
contains all the details about the name, colors, size etc. Based
on these descriptions, we can study about the parrot. Here, a
parrot is an object.
Example:
class Parrot:
pass
 Here, we use the class keyword to define an empty
class Parrot. From class, we construct instances. An instance
is a specific object created from a particular class.
Creating Class and Object in Python
 # define a class
 class Bike:
 name = ""
 gear = 0
 # create object of class
 bike1 = Bike()
 # access attributes and assign new values
 bike1.gear = 11
 bike1.name = "Mountain Bike"
 print(f"Name: {bike1.name}, Gears: {bike1.gear} ")
 Output:
 Name: Mountain Bike, Gears: 11
Example: class
 Create a class named Person, use the __init__() function to assign
values for name and age:
 class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
 Output:
 John
 36
 Note: The __init__() function is called automatically every time the
class is being used to create a new object.
 The self parameter is a reference to the current instance of the class,
and is used to access variables that belong to the class.
Object Methods
 Objects can also contain methods. Methods in objects are
functions that belong to the object.
 Let us create a method in the Person class:
Example:
Insert a function that prints a greeting, and execute it on the p1
object:
 class Person:
def __init__(self, name):
self.name = name
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John")
p1.myfunc()
 Output: Hello my name is John
Modify objects:
 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.age = 40
 print(p1.age)
 Output:40
Delete Object Properties
 you can delete properties on objects by using
the del keyword:
 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)
 #del p1.age
 #del p1
 print(p1.age)
Inheritance in python
 Inheritance allows us to define a class that inherits all
the methods and properties from another class.
 Parent class is the class being inherited from, also
called base class.
 Child class is the class that inherits from another class,
also called derived class.
Example:
Example:
 class Animal:
 def speak(self):
 print("Animal Speaking")
#child class Dog inherits the base class Animal
 class Dog(Animal):
 def bark(self):
 print("dog barking")
 d = Dog()
 d.bark()
 d.speak()
Output:
dog barking
Animal Speaking
Python Multi-Level inheritance
 Multi-Level inheritance is possible in python like other
object-oriented languages.
 Multi-level inheritance is archived when a derived class
inherits another derived class.
 There is no limit on the number of levels up to which,
the multi-level inheritance is archived in python.
Example
 class Animal:
 def speak(self):
 print("Animal Speaking")
 #The child class Dog inherits the base class Animal
 class Dog(Animal):
 def bark(self):
 print("dog barking")
 #The child class Dogchild inherits another child class Dog
 class DogChild(Dog):
 def eat(self):
 print("Eating bread...")
 d = DogChild()
 d.bark()
 d.speak()
 d.eat()
Output:
 dog barking
 Animal Speaking
 Eating bread...
Python Multiple inheritance
 Python provides us the flexibility to inherit multiple base
classes in the child class.
Syntax:
 class Base1:
 <class-suite>

 class Base2:
 <class-suite>
 class BaseN:
 <class-suite>

 class Derived(Base1, Base2, ...... BaseN):
 <class-suite>
Example:
 class Calculation1:
 def Summation(self,a,b):
 return a+b;
 class Calculation2:
 def Multiplication(self,a,b):
 return a*b;
 class Derived(Calculation1,Calculation2):
 def Divide(self,a,b):
 return a/b;
 d = Derived()
 print(d.Summation(10,20))
 print(d.Multiplication(10,20))
 print(d.Divide(10,20))
 Output:
 30 200 0.5
Hierarchical Inheritance:
 When more than one derived class are created from a single base
this type of inheritance is called hierarchical inheritance. In this
program, we have a parent (base) class and two child (derived)
classes.
Example:
 # Base class
 class Parent:
 def func1(self):
 print("This function is in parent class.")

 # Derived class1
 class Child1(Parent):
 def func2(self):
 print("This function is in child 1.")

 # Derivied class2
 class Child2(Parent):
 def func3(self):
 print("This function is in child 2.")
 # Driver's code
 object1 = Child1()
 object2 = Child2()
 object1.func1()
 object1.func2()
 object2.func1()
 object2.func3()
 Output:
 This function is in parent class.
 This function is in child 1.
 This function is in parent class.
 This function is in child 2.
Hybrid Inheritance:
 Inheritance consisting of multiple types of inheritance is called
hybrid inheritance.
Example:
 class School:
 def func1(self):
 print("This function is in school.")

 class Student1(School):
 def func2(self):
 print("This function is in student 1. ")

 class Student2(School):
 def func3(self):
 print("This function is in student 2.")
 class Student3(Student1, School):
 def func4(self):
 print("This function is in student 3.")

 # Driver's code
 object = Student3()
 object.func1()
 object.func2()
 Output:
 This function is in school.
 This function is in student 1.
What is Polymorphism?
 The literal meaning of polymorphism is the condition of occurrence
in different forms.
 Polymorphism is a very important concept in programming. It refers
to the use of a single type entity (method, operator or object) to
represent different types in different scenarios.
 Let's take an example:
Example 1: Polymorphism in addition operator
 We know that the + operator is used extensively in Python
programs. But, it does not have a single usage.
 For integer data types, + operator is used to perform arithmetic
addition operation.
 num1 = 1
 num2 = 2
 print(num1+num2)
 Output:3
Cont..
 Similarly, for string data types, + operator is used to
perform concatenation.
 str1 = "Python"
 str2 = "Programming"
 print(str1+" "+str2)
 Output: Python Programming
 As a result, the above program outputs Python
Programming.
 Here, we can see that a single operator + has been
used to carry out different operations for distinct
data types. This is one of the most simple
occurrences of polymorphism in Python.
Function Polymorphism in Python
 There are some functions in Python which are
compatible to run with multiple data types.
 One such function is the len() function. It can run with
many data types in Python. Let's look at some example
use cases of the function.
 print(len("Programiz"))
 print(len(["Python", "Java", "C"]))
 print(len({"Name": "John", "Address": "Nepal"}))
 Output: 9 3 2
Class Polymorphism in Python
 We can use the concept of polymorphism while creating
class methods as Python allows different classes to have
methods with the same name.
 We can then later generalize calling these methods by
disregarding the object we are working with. Let's look
at an example:
Example 3: Polymorphism in Class Methods
 class Cat:
 def __init__(self, name, age):
 self.name = name
 self.age = age
 def info(self):
 print(f"I am a cat. My name is {self.name}. I am
{self.age} years old.")
 def make_sound(self):
 print("Meow")
 class Dog:
 def __init__(self, name, age):
 self.name = name
 self.age = age
Cont..
 def info(self):
 print(f"I am a dog. My name is {self.name}. I am
{self.age} years old.")
 def make_sound(self):
 print("Bark")
 cat1 = Cat("Kitty", 2.5)
 dog1 = Dog("Fluffy", 4)
 for animal in (cat1, dog1):
 animal.make_sound()
 animal.info()
 animal.make_sound()
 Output:Meow I am a cat. My name is Kitty. I am 2.5 years
old. Meow Bark I am a dog. My name is Fluffy. I am 4 years
old. Bark
Polymorphism and Inheritance
 Like in other programming languages, the child classes
in Python also inherit methods and attributes from the
parent class. We can redefine certain methods and
attributes specifically to fit the child class, which is
known as Method Overriding.
 Polymorphism allows us to access these overridden
methods and attributes that have the same name as the
parent class.
Method Overriding
Cont..
 # Defining parent class
 class Parent():
 # Constructor
 def __init__(self):
 self.value = "Inside Parent"

 # Parent's show method
 def show(self):
 print(self.value)

 # Defining child class
 class Child(Parent):

 # Constructor
 def __init__(self):
 self.value = "Inside Child"

 # Child's show method
 def show(self):
 print(self.value)
 # Driver's code
 obj1 = Parent()
 obj2 = Child()
 obj1.show()
 obj2.show()
 Output:
 Inside parent
 Inside child
Cont..
 Note: Method Overloading, a way to create multiple
methods with the same name but different arguments, is
not possible in Python.
Python Operator Overloading
 Operator Overloading means giving extended meaning beyond their predefined
operational meaning. For example operator + is used to add two integers as well
as join two strings and merge two lists. It is achievable because ‘+’ operator is
overloaded by int class and str class. You might have noticed that the same built-
in operator or function shows different behavior for objects of different classes, this
is called Operator Overloading.
 # Python program to show use of
 # + operator for different purposes.

 print(1 + 2)
 # concatenate two strings
 print("Geeks"+"For")

 # Product two numbers
 print(3 * 4)

 # Repeat the String
 print("Geeks"*4)
 Output
 3
 GeeksFor
 12
 GeeksGeeksGeeksGeeks
Example:
 class Point:
 def __init__(self, x=0, y=0):
 self.x = x
 self.y = y
 p1 = Point(1, 2)
 p2 = Point(2, 3)
 print(p1+p2)
 Output:
 Traceback (most recent call last): File "<string>", line 9, in <module>
print(p1+p2) TypeError: unsupported operand type(s) for +: 'Point'
and 'Point'
Overloading the + Operator
 To overload the + operator, we will need to implement __add__() function in the
class. With great power comes great responsibility. We can do whatever we like,
inside this function. But it is more sensible to return a Point object of the coordinate
sum.
 class Point:
 def __init__(self, x=0, y=0):
 self.x = x
 self.y = y
 def __add__(self, other):
 x = self.x + other.x
 y = self.y + other.y
 return Point(x, y)
 p1 = Point(1, 2)
 p2 = Point(2, 3)
 print(p1+p2)
 Output:(3,5)
 What actually happens is that, when you use p1 + p2, Python
calls p1.__add__(p2) which in turn is Point.__add__(p1,p2). After this, the
addition operation is carried out the way we specified.
Overloading comparison operators in Python :
 class A:
 def __init__(self, a):
 self.a = a
 def __gt__(self, other):
 if(self.a>other.a):
 return True
 else:
 return False
 ob1 = A(2)
 ob2 = A(3)
 if(ob1>ob2):
 print("ob1 is greater than ob2")
 else:
 print("ob2 is greater than ob1")
 Output:
 ob2 is greater than ob1
Other operators using
overloading
 Similarly, we can overload other operators as well. The special
function that we need to implement is tabulated below.
Operator Expression Internally
Addition p1 + p2
p1.__add__(p2
)
Subtraction p1 - p2 p1.__sub__(p2)
Multiplication p1 * p2 p1.__mul__(p2)
Power p1 ** p2
p1.__pow__(p2
)
Division p1 / p2
p1.__truediv__(
p2)
Floor Division p1 // p2
p1.__floordiv__
(p2)
Remainder p1.__mod__(p2
Bitwise operators:
Bitwise Left Shift p1 << p2 p1.__lshift__(p2)
Bitwise Right Shift p1 >> p2 p1.__rshift__(p2)
Bitwise AND p1 & p2 p1.__and__(p2)
Bitwise OR p1 | p2 p1.__or__(p2)
Bitwise XOR p1 ^ p2 p1.__xor__(p2)
Bitwise NOT ~p1 p1.__invert__()
Overloading Comparison Operators
 Python does not limit operator overloading to arithmetic operators only.
We can overload comparison operators as well.
 Suppose we wanted to implement the less than symbol < symbol in
our Point class.
Operator Expression Internally
Less than p1 < p2 p1.__lt__(p2)
Less than or equal to p1 <= p2 p1.__le__(p2)
Equal to p1 == p2 p1.__eq__(p2)
Not equal to p1 != p2 p1.__ne__(p2)
Greater than p1 > p2 p1.__gt__(p2)
Greater than or
equal to
p1 >= p2 p1.__ge__(p2)
Assignment Operators:
Getter and setter:
 Getters:-
 These are the methods used in Object-Oriented
Programming (OOPS) which helps to access the private
attributes from a class.
 Setters:-
 These are the methods used in OOPS feature which
helps to set the value to private attributes in a class.
Private Attribute - Encapsulation
 Let's see how you can implement a private attribute
in Python.
 class SampleClass:
 def __init__(self, a):
 ## private varibale or property in Python
 self.__a = a
 ## getter method to get the properties using an
object
 def get_a(self):
 return self.__a
 ## setter method to change the value 'a' using an
object
 def set_a(self, a):
 self.__a = a
Explanation:
 __init__:- It is used to initialize the attributes or
properties of a class.
◦ __a:- It is a private attribute.
 get_a:- It is used to get the values of private attribute a.
 set_a:- It is used to set the value of a using an object of
a class.
 You are not able to access the private variables directly
in Python. That's why you implemented
the getter method.
Cont.
 Let's see how the class works.
 ## creating an object
 obj = SampleClass(10)
 ## getting the value of 'a' using get_a() method
 print(obj.get_a())
 ## setting a new value to the 'a' using set_a() method
 obj.set_a(45)
 print(obj.get_a())
 Output: 10 45
Pythonic way
 This is how you implement private attributes, getters,
and setters in Python. The same process was followed
in Java. Let's write the same implementation in
a Pythonic way.
 class PythonicWay:
 def __init__(self, a):
 self.a = a
 You don't need any getters, setters methods to access or
change the attributes. You can access it directly using the
name of the attributes.
What's the difference between the above two
classes.
 SampleClass hides the private attributes and methods. It
implements the encapsulation feature of OOPS.
 PythonicWay doesn't hide the data. It doesn't
implement any encapsulation feature.
What's the better to use?
 This depends on our need. If you want private attributes
and methods you can implement the class using setters,
getters methods otherwise you will implement using the
normal way.
The @property Decorator
 In Python, property() is a built-in function that creates
and returns a property object. The syntax of this function
is:
 property(fget=None, fset=None, fdel=None, doc=None)
 where,
 fget is function to get value of the attribute
 fset is function to set value of the attribute
 fdel is function to delete the attribute
 doc is a string (like a comment)
 A property object has three
methods, getter(), setter(), and deleter() to
specify fget, fset and fdel at a later point. This
means, the line:
Example program:
 # Using @property decorator
 class Celsius:
 def __init__(self, temperature=0):
 self.temperature = temperature
 def to_fahrenheit(self):
 return (self.temperature * 1.8) + 32
 @property
 def temperature(self):
 print("Getting value...")
 return self._temperature
 @temperature.setter
 def temperature(self, value):
 print("Setting value...")
 if value < -273.15:
 raise ValueError("Temperature below -273 is not possible")
 self._temperature = value
Cont.
 # create an object
 human = Celsius(37)
 print(human.temperature)
 print(human.to_fahrenheit())
 coldest_thing = Celsius(-300)
 Output:
 Setting value...
 Getting value...
 37 Getting value...
 98.60000000000001
 Setting value
 Temperature below -273 is not possible
 The above implementation is simple and efficient. It is the
recommended way to use property.
What is duck typing
 It is a popular term in Python, and it comes from
saying, "If it walks like duck, swims like duck, looks
like a duck, then it probably should be a duck."
 The above statement gives an idea to identify a duck.
Here we don't need to have a genomic sequence of the
duck.
 We draw our conclusion by its behavior and external
appearances.
 Python follows the EAFP (Easier to Ask Forgiveness
than Permission) rather than the LBLY (Look Before
You Leap) philosophy.
 The EAFP is somewhat linked to the "duck typing"
style.
Dynamic vs. Static Typing
 The main reason for using duck typing is to provide
support for dynamic typing in Python programming.
 In Python, we don't need to specify the variable's data
type and we can reassign the different data type values
to same variable in further code.
 Example
 x = 12000
 print(type(x))

 x = 'Dynamic Typing'
 print(type(x))

 x = [1, 2, 3, 4]
 print(type(x))
 Output:<class 'int'> <class 'str'> <class 'list'>
Cont.
 As we can see in the above code, we assigned an
integer to a variable x, making it of the int type.
Then, we assigned a string and a list to the same
variable.
 Python interpreter accepts the changes of data types
of the same variable. This is a dynamic typing
behavior.
 Many other programming languages such as Java,
swift are the static type.
 We need to declare variable with the data types. In
the below example, we try to do the same thing
using the Swift instead of Python.
Example
 # integer value assigning in JavaScript
 var a = 10

 # Assinging string in swift
 a = 'Swift language'
 Above code cannot be compiled, because we
couldn't assign a string in Swift language.
Because variable a was declared as an integer.
Concept of Duck Typing
 Earlier, we have discussed that Python is a dynamic typed
language. However, we can use the dynamic approach with
custom data types. Let's understand the following example.
 class VisualStudio:
 def execute(self):
 print('Compiling')
 print('Running')
 print('Spell Check')
 print('Convention Check')
 class Desktop:
 def code(self, ide):
 ide.execute()
 ide = VisualStudio()
 desk = Desktop()
 desk.code(ide)
Output:
 Compiling
 Running
 Spell Check
 Convention Check
 In the above code, we have created a VisualStudio class
that has to execute() method.
 In the desktop-class, we have passed the ide as an
argument in the code().
 An ide is an object of VisualStudio class. With the help
of ide,
 we called the execute() method of VisualStudio class.
How duck typing supports EAFP
 The duck typing is the most appropriate style for the
EAFP because we don't need to focus on the "type" of
the object. We only need to take care of
its behavior and capability. Let's see the following
statements.
 When we see a lot of if-else blocks, then it is an LBYL
coding style.
 But if we see a lot of try-except blocks, then it is a
probability an EAFP coder.
Name mangling in Python
 In name mangling process any identifier with two
leading underscore and one trailing underscore is
textually replaced with _classname__identifier where
classname is the name of the current class.
 It means that any identifier of the form __geek (at least
two leading underscores or at most one trailing
underscore) is replaced with _classname__geek, where
classname is the current class name with leading
underscore(s) stripped.
Example:
 # Python program to demonstrate
 # name mangling
 class Student:
 def __init__(self, name):
 self.__name = name
 def displayName(self):
 print(self.__name)
 s1 = Student(“Keerthi")
 s1.displayName()
 # Raises an error
 print(s1.__name)
Output
 Keerthi
 Traceback (most recent call last): File
"/home/be691046ea08cd2db075d27186ea0493.py", line
14, in print(s1.__name) AttributeError: 'Student' object
has no attribute '__name‘
 In the above example, the class variable __name is not
accessible outside the class. It can be accessed only
within the class. Any modification of the class variable
can be done only inside the class.
Name mangling process
 With the help of dir() method, we can see the name mangling
process that is done to the class variable.
 The name mangling process was done by the Interpreter.
 The dir() method is used by passing the class object and it
will return all valid attributes that belong to that object.
 # Python program to demonstrate
 # name mangling
 class Student:
 def __init__(self, name):
 self.__name = name
 s1 = Student("Santhosh")
 print(dir(s1))
Output
 [‘_Student__name’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’,
‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’,
‘__hash__’, ‘__init__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’,
‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’,
‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’]
 The above output shows dir() method returning all valid
attributes with the name mangling process that is done to
the class variable __name. The name changed from
__name to _Student__name.
Accessing Name Mangled variables
 The name mangling process helps to access the class
variables from outside the class. The class variables can
be accessed by adding _classname to it. The name
mangling is closest to private not exactly private.
 # Python program to demonstrate
 # name mangling
 class Student:
 def __init__(self, name):
 self.__name = name
 s1 = Student(“keerthi")
 print(s1._Student__name) output:keerthi
 The above class variable is accessed by adding the
_classname to it. The class variable is accessed from
outside the class with the name _Student__name.
Relationships in class
 in object-oriented programming, there are three
relationships between classes : dependencies 、
combination relationship ,inheritance relationship.
Dependencies:
passing the class name or object of one class as aparameter
to another function is a dependency.
class People:
def __init__(self,name):
self.name = name
def open(self,bx):
bx.open_door(self)
def close(self,bx):
bx.close_door(self)
Cont..
 class Refrigerator:
 def __init__(self,name):
 self.name = name def open_door(self,p):
 print(f"{p.name} open the refrigerator ")
 def close_door(self,p):
 print(f"{p.name} close the refrigerator ")
 r = People(" big magic ")
 # People class instantiates an object r
 aux = Refrigerator(" oakes ")
 # Refrigerator class instantiates an object, aux r.open(aux)
 # pass the aux object as a parameter to r object is used by the
open method r.close(aux)
 # pass the aux object as a parameter to r object is used by the
close method
combination relationship
 encapsulating objects of one class into attributes of
objects of another class is called composition
 class Boy:
 def __init__(self,name,g):
 self.name = name # self = b
 self.g = g # g is an object memory address that
the girl class instantiates
 def eat(self):
 print(f"{self.name} and {self.g.age} years old,
and {self.g.weight} kg, {self.g.name}py friends. we
had a candlelight dinner together !") def
make_keep(self): self.g.live(f"{self.g.weight} kg,
{self.g.name} to {self.name} on the back ")
Cont..
 class Girl:
 def __init__(self,name,age,sex,weight,*args):
 self.name = name
 self.age = age
 self.gender = gender
 self.weight = weight
 self.args = args
 def live(self,argv): print(f" live content :{argv}")
 g = Girl(" joe never put off till tomorrow what you can
get ",54," female ",220)
 b = Boy(" so bo ",g) # encapsulates object g as a
property b object b.make_keep()
inheritance relationships
 inheritance ( english :inheritance) is a concept in
object-oriented software technology.
 if a category A“ inherited from ” another category b, just
take this one A referred to as “B the subcategory ”,
let's call b “A the parent category ” can also be said “B
it's a superclass of a ”
 inheritance enables subcategories to have the various
attributes and methods of the parent without having to
write the same code again
Example: without inheritance
 class Human:
 def __init__(self,name,age,gender):
 self.name = name
 self. gender = gender
 self.age = age
 def eat(self):
 print(" eat ")
 class Dog:
 def __init__(self, name, age, gender):
 self.name = name
 self. gender = gender
 self.age = age
 def eat(self): print(" eat ")
class Cat:
 def __init__(self, name, age, gender):
 self.name = name
 self. gender = gender
 self.age = age
 def eat(self): print(" eat ")
Example:inheritance
 class Animal: # the parent class
 """ animal """
 live = " live “
 def __init__(self, name, age, gender):
 print("is __init__")
 self.name = name
 self. gender = gender
 self.age = age
 def eat(self): # self is the position parameter of the function
 print(" eat ")
 class Human(Animal): # a subclass
 pass class
 Dog(Animal): # a subclass
 Pass
 class Cat(Animal): # a subclass pass
THANK YOU

More Related Content

Similar to Python programming computer science and engineering (20)

python note.pdf
python note.pdfpython note.pdf
python note.pdf
Nagendra504676
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
Ahmad Hussein
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
Mohd Aves Malik
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptxoogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
BhojarajTheking
 
Dps_Python1_Ectracted_2345633_Pptx4.pptx
Dps_Python1_Ectracted_2345633_Pptx4.pptxDps_Python1_Ectracted_2345633_Pptx4.pptx
Dps_Python1_Ectracted_2345633_Pptx4.pptx
ecomwithfaith
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. Polymorphism
AndiNurkholis1
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
Sasidhar Kothuru
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
Sasidhar Kothuru
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
talha ijaz
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
Ahmad Hussein
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptxoogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
BhojarajTheking
 
Dps_Python1_Ectracted_2345633_Pptx4.pptx
Dps_Python1_Ectracted_2345633_Pptx4.pptxDps_Python1_Ectracted_2345633_Pptx4.pptx
Dps_Python1_Ectracted_2345633_Pptx4.pptx
ecomwithfaith
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. Polymorphism
AndiNurkholis1
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 

Recently uploaded (20)

Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
How to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time OffHow to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time Off
Celine George
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Fatman Book HD Pdf by aayush songare.pdf
Fatman Book  HD Pdf by aayush songare.pdfFatman Book  HD Pdf by aayush songare.pdf
Fatman Book HD Pdf by aayush songare.pdf
Aayush Songare
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
SweetytamannaMohapat
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
How to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time OffHow to Manage Allocations in Odoo 18 Time Off
How to Manage Allocations in Odoo 18 Time Off
Celine George
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Fatman Book HD Pdf by aayush songare.pdf
Fatman Book  HD Pdf by aayush songare.pdfFatman Book  HD Pdf by aayush songare.pdf
Fatman Book HD Pdf by aayush songare.pdf
Aayush Songare
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
SweetytamannaMohapat
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
Ad

Python programming computer science and engineering

  • 2. Object Oriented Programming  Python is a multi-paradigm programming language. It supports different programming approaches.  One of the popular approaches to solve a programming problem is by creating objects. This is known as Object- Oriented Programming (OOP).  An object has two characteristics:  attributes  behavior Let's take an example:  A parrot is an object, as it has the following properties:  name, age, color as attributes  singing, dancing as behavior  The concept of OOP in Python focuses on creating reusable code. This concept is also known as DRY (Don't Repeat Yourself).
  • 3. Object  An object (instance) is an instantiation of a class. When class is defined, only the description for the object is defined. Therefore, no memory or storage is allocated. The example for object of parrot class can be:  obj = Parrot()  Here, obj is an object of class Parrot.
  • 4. Class  In Python, the concept of OOP follows some basic principles:  A class is a blueprint for the object.  We can think of class as a sketch of a parrot with labels. It contains all the details about the name, colors, size etc. Based on these descriptions, we can study about the parrot. Here, a parrot is an object. Example: class Parrot: pass  Here, we use the class keyword to define an empty class Parrot. From class, we construct instances. An instance is a specific object created from a particular class.
  • 5. Creating Class and Object in Python  # define a class  class Bike:  name = ""  gear = 0  # create object of class  bike1 = Bike()  # access attributes and assign new values  bike1.gear = 11  bike1.name = "Mountain Bike"  print(f"Name: {bike1.name}, Gears: {bike1.gear} ")  Output:  Name: Mountain Bike, Gears: 11
  • 6. Example: class  Create a class named Person, use the __init__() function to assign values for name and age:  class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)  Output:  John  36  Note: The __init__() function is called automatically every time the class is being used to create a new object.  The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
  • 7. Object Methods  Objects can also contain methods. Methods in objects are functions that belong to the object.  Let us create a method in the Person class: Example: Insert a function that prints a greeting, and execute it on the p1 object:  class Person: def __init__(self, name): self.name = name def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John") p1.myfunc()  Output: Hello my name is John
  • 8. Modify objects:  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.age = 40  print(p1.age)  Output:40
  • 9. Delete Object Properties  you can delete properties on objects by using the del keyword:  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)  #del p1.age  #del p1  print(p1.age)
  • 10. Inheritance in python  Inheritance allows us to define a class that inherits all the methods and properties from another class.  Parent class is the class being inherited from, also called base class.  Child class is the class that inherits from another class, also called derived class.
  • 12. Example:  class Animal:  def speak(self):  print("Animal Speaking") #child class Dog inherits the base class Animal  class Dog(Animal):  def bark(self):  print("dog barking")  d = Dog()  d.bark()  d.speak() Output: dog barking Animal Speaking
  • 13. Python Multi-Level inheritance  Multi-Level inheritance is possible in python like other object-oriented languages.  Multi-level inheritance is archived when a derived class inherits another derived class.  There is no limit on the number of levels up to which, the multi-level inheritance is archived in python.
  • 14. Example  class Animal:  def speak(self):  print("Animal Speaking")  #The child class Dog inherits the base class Animal  class Dog(Animal):  def bark(self):  print("dog barking")  #The child class Dogchild inherits another child class Dog  class DogChild(Dog):  def eat(self):  print("Eating bread...")  d = DogChild()  d.bark()  d.speak()  d.eat() Output:  dog barking  Animal Speaking  Eating bread...
  • 15. Python Multiple inheritance  Python provides us the flexibility to inherit multiple base classes in the child class. Syntax:  class Base1:  <class-suite>   class Base2:  <class-suite>  class BaseN:  <class-suite>   class Derived(Base1, Base2, ...... BaseN):  <class-suite>
  • 16. Example:  class Calculation1:  def Summation(self,a,b):  return a+b;  class Calculation2:  def Multiplication(self,a,b):  return a*b;  class Derived(Calculation1,Calculation2):  def Divide(self,a,b):  return a/b;  d = Derived()  print(d.Summation(10,20))  print(d.Multiplication(10,20))  print(d.Divide(10,20))  Output:  30 200 0.5
  • 17. Hierarchical Inheritance:  When more than one derived class are created from a single base this type of inheritance is called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes.
  • 18. Example:  # Base class  class Parent:  def func1(self):  print("This function is in parent class.")   # Derived class1  class Child1(Parent):  def func2(self):  print("This function is in child 1.")   # Derivied class2  class Child2(Parent):  def func3(self):  print("This function is in child 2.")  # Driver's code  object1 = Child1()  object2 = Child2()  object1.func1()  object1.func2()  object2.func1()  object2.func3()  Output:  This function is in parent class.  This function is in child 1.  This function is in parent class.  This function is in child 2.
  • 19. Hybrid Inheritance:  Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
  • 20. Example:  class School:  def func1(self):  print("This function is in school.")   class Student1(School):  def func2(self):  print("This function is in student 1. ")   class Student2(School):  def func3(self):  print("This function is in student 2.")  class Student3(Student1, School):  def func4(self):  print("This function is in student 3.")   # Driver's code  object = Student3()  object.func1()  object.func2()  Output:  This function is in school.  This function is in student 1.
  • 21. What is Polymorphism?  The literal meaning of polymorphism is the condition of occurrence in different forms.  Polymorphism is a very important concept in programming. It refers to the use of a single type entity (method, operator or object) to represent different types in different scenarios.  Let's take an example: Example 1: Polymorphism in addition operator  We know that the + operator is used extensively in Python programs. But, it does not have a single usage.  For integer data types, + operator is used to perform arithmetic addition operation.  num1 = 1  num2 = 2  print(num1+num2)  Output:3
  • 22. Cont..  Similarly, for string data types, + operator is used to perform concatenation.  str1 = "Python"  str2 = "Programming"  print(str1+" "+str2)  Output: Python Programming  As a result, the above program outputs Python Programming.  Here, we can see that a single operator + has been used to carry out different operations for distinct data types. This is one of the most simple occurrences of polymorphism in Python.
  • 23. Function Polymorphism in Python  There are some functions in Python which are compatible to run with multiple data types.  One such function is the len() function. It can run with many data types in Python. Let's look at some example use cases of the function.  print(len("Programiz"))  print(len(["Python", "Java", "C"]))  print(len({"Name": "John", "Address": "Nepal"}))  Output: 9 3 2
  • 24. Class Polymorphism in Python  We can use the concept of polymorphism while creating class methods as Python allows different classes to have methods with the same name.  We can then later generalize calling these methods by disregarding the object we are working with. Let's look at an example:
  • 25. Example 3: Polymorphism in Class Methods  class Cat:  def __init__(self, name, age):  self.name = name  self.age = age  def info(self):  print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")  def make_sound(self):  print("Meow")  class Dog:  def __init__(self, name, age):  self.name = name  self.age = age
  • 26. Cont..  def info(self):  print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")  def make_sound(self):  print("Bark")  cat1 = Cat("Kitty", 2.5)  dog1 = Dog("Fluffy", 4)  for animal in (cat1, dog1):  animal.make_sound()  animal.info()  animal.make_sound()  Output:Meow I am a cat. My name is Kitty. I am 2.5 years old. Meow Bark I am a dog. My name is Fluffy. I am 4 years old. Bark
  • 27. Polymorphism and Inheritance  Like in other programming languages, the child classes in Python also inherit methods and attributes from the parent class. We can redefine certain methods and attributes specifically to fit the child class, which is known as Method Overriding.  Polymorphism allows us to access these overridden methods and attributes that have the same name as the parent class.
  • 29. Cont..  # Defining parent class  class Parent():  # Constructor  def __init__(self):  self.value = "Inside Parent"   # Parent's show method  def show(self):  print(self.value)   # Defining child class  class Child(Parent):   # Constructor  def __init__(self):  self.value = "Inside Child"   # Child's show method  def show(self):  print(self.value)  # Driver's code  obj1 = Parent()  obj2 = Child()  obj1.show()  obj2.show()  Output:  Inside parent  Inside child
  • 30. Cont..  Note: Method Overloading, a way to create multiple methods with the same name but different arguments, is not possible in Python.
  • 31. Python Operator Overloading  Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built- in operator or function shows different behavior for objects of different classes, this is called Operator Overloading.  # Python program to show use of  # + operator for different purposes.   print(1 + 2)  # concatenate two strings  print("Geeks"+"For")   # Product two numbers  print(3 * 4)   # Repeat the String  print("Geeks"*4)  Output  3  GeeksFor  12  GeeksGeeksGeeksGeeks
  • 32. Example:  class Point:  def __init__(self, x=0, y=0):  self.x = x  self.y = y  p1 = Point(1, 2)  p2 = Point(2, 3)  print(p1+p2)  Output:  Traceback (most recent call last): File "<string>", line 9, in <module> print(p1+p2) TypeError: unsupported operand type(s) for +: 'Point' and 'Point'
  • 33. Overloading the + Operator  To overload the + operator, we will need to implement __add__() function in the class. With great power comes great responsibility. We can do whatever we like, inside this function. But it is more sensible to return a Point object of the coordinate sum.  class Point:  def __init__(self, x=0, y=0):  self.x = x  self.y = y  def __add__(self, other):  x = self.x + other.x  y = self.y + other.y  return Point(x, y)  p1 = Point(1, 2)  p2 = Point(2, 3)  print(p1+p2)  Output:(3,5)  What actually happens is that, when you use p1 + p2, Python calls p1.__add__(p2) which in turn is Point.__add__(p1,p2). After this, the addition operation is carried out the way we specified.
  • 34. Overloading comparison operators in Python :  class A:  def __init__(self, a):  self.a = a  def __gt__(self, other):  if(self.a>other.a):  return True  else:  return False  ob1 = A(2)  ob2 = A(3)  if(ob1>ob2):  print("ob1 is greater than ob2")  else:  print("ob2 is greater than ob1")  Output:  ob2 is greater than ob1
  • 35. Other operators using overloading  Similarly, we can overload other operators as well. The special function that we need to implement is tabulated below. Operator Expression Internally Addition p1 + p2 p1.__add__(p2 ) Subtraction p1 - p2 p1.__sub__(p2) Multiplication p1 * p2 p1.__mul__(p2) Power p1 ** p2 p1.__pow__(p2 ) Division p1 / p2 p1.__truediv__( p2) Floor Division p1 // p2 p1.__floordiv__ (p2) Remainder p1.__mod__(p2
  • 36. Bitwise operators: Bitwise Left Shift p1 << p2 p1.__lshift__(p2) Bitwise Right Shift p1 >> p2 p1.__rshift__(p2) Bitwise AND p1 & p2 p1.__and__(p2) Bitwise OR p1 | p2 p1.__or__(p2) Bitwise XOR p1 ^ p2 p1.__xor__(p2) Bitwise NOT ~p1 p1.__invert__()
  • 37. Overloading Comparison Operators  Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.  Suppose we wanted to implement the less than symbol < symbol in our Point class. Operator Expression Internally Less than p1 < p2 p1.__lt__(p2) Less than or equal to p1 <= p2 p1.__le__(p2) Equal to p1 == p2 p1.__eq__(p2) Not equal to p1 != p2 p1.__ne__(p2) Greater than p1 > p2 p1.__gt__(p2) Greater than or equal to p1 >= p2 p1.__ge__(p2)
  • 39. Getter and setter:  Getters:-  These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class.  Setters:-  These are the methods used in OOPS feature which helps to set the value to private attributes in a class.
  • 40. Private Attribute - Encapsulation  Let's see how you can implement a private attribute in Python.  class SampleClass:  def __init__(self, a):  ## private varibale or property in Python  self.__a = a  ## getter method to get the properties using an object  def get_a(self):  return self.__a  ## setter method to change the value 'a' using an object  def set_a(self, a):  self.__a = a
  • 41. Explanation:  __init__:- It is used to initialize the attributes or properties of a class. ◦ __a:- It is a private attribute.  get_a:- It is used to get the values of private attribute a.  set_a:- It is used to set the value of a using an object of a class.  You are not able to access the private variables directly in Python. That's why you implemented the getter method.
  • 42. Cont.  Let's see how the class works.  ## creating an object  obj = SampleClass(10)  ## getting the value of 'a' using get_a() method  print(obj.get_a())  ## setting a new value to the 'a' using set_a() method  obj.set_a(45)  print(obj.get_a())  Output: 10 45
  • 43. Pythonic way  This is how you implement private attributes, getters, and setters in Python. The same process was followed in Java. Let's write the same implementation in a Pythonic way.  class PythonicWay:  def __init__(self, a):  self.a = a  You don't need any getters, setters methods to access or change the attributes. You can access it directly using the name of the attributes.
  • 44. What's the difference between the above two classes.  SampleClass hides the private attributes and methods. It implements the encapsulation feature of OOPS.  PythonicWay doesn't hide the data. It doesn't implement any encapsulation feature. What's the better to use?  This depends on our need. If you want private attributes and methods you can implement the class using setters, getters methods otherwise you will implement using the normal way.
  • 45. The @property Decorator  In Python, property() is a built-in function that creates and returns a property object. The syntax of this function is:  property(fget=None, fset=None, fdel=None, doc=None)  where,  fget is function to get value of the attribute  fset is function to set value of the attribute  fdel is function to delete the attribute  doc is a string (like a comment)  A property object has three methods, getter(), setter(), and deleter() to specify fget, fset and fdel at a later point. This means, the line:
  • 46. Example program:  # Using @property decorator  class Celsius:  def __init__(self, temperature=0):  self.temperature = temperature  def to_fahrenheit(self):  return (self.temperature * 1.8) + 32  @property  def temperature(self):  print("Getting value...")  return self._temperature  @temperature.setter  def temperature(self, value):  print("Setting value...")  if value < -273.15:  raise ValueError("Temperature below -273 is not possible")  self._temperature = value
  • 47. Cont.  # create an object  human = Celsius(37)  print(human.temperature)  print(human.to_fahrenheit())  coldest_thing = Celsius(-300)  Output:  Setting value...  Getting value...  37 Getting value...  98.60000000000001  Setting value  Temperature below -273 is not possible  The above implementation is simple and efficient. It is the recommended way to use property.
  • 48. What is duck typing  It is a popular term in Python, and it comes from saying, "If it walks like duck, swims like duck, looks like a duck, then it probably should be a duck."  The above statement gives an idea to identify a duck. Here we don't need to have a genomic sequence of the duck.  We draw our conclusion by its behavior and external appearances.  Python follows the EAFP (Easier to Ask Forgiveness than Permission) rather than the LBLY (Look Before You Leap) philosophy.  The EAFP is somewhat linked to the "duck typing" style.
  • 49. Dynamic vs. Static Typing  The main reason for using duck typing is to provide support for dynamic typing in Python programming.  In Python, we don't need to specify the variable's data type and we can reassign the different data type values to same variable in further code.  Example  x = 12000  print(type(x))   x = 'Dynamic Typing'  print(type(x))   x = [1, 2, 3, 4]  print(type(x))  Output:<class 'int'> <class 'str'> <class 'list'>
  • 50. Cont.  As we can see in the above code, we assigned an integer to a variable x, making it of the int type. Then, we assigned a string and a list to the same variable.  Python interpreter accepts the changes of data types of the same variable. This is a dynamic typing behavior.  Many other programming languages such as Java, swift are the static type.  We need to declare variable with the data types. In the below example, we try to do the same thing using the Swift instead of Python.
  • 51. Example  # integer value assigning in JavaScript  var a = 10   # Assinging string in swift  a = 'Swift language'  Above code cannot be compiled, because we couldn't assign a string in Swift language. Because variable a was declared as an integer.
  • 52. Concept of Duck Typing  Earlier, we have discussed that Python is a dynamic typed language. However, we can use the dynamic approach with custom data types. Let's understand the following example.  class VisualStudio:  def execute(self):  print('Compiling')  print('Running')  print('Spell Check')  print('Convention Check')  class Desktop:  def code(self, ide):  ide.execute()  ide = VisualStudio()  desk = Desktop()  desk.code(ide)
  • 53. Output:  Compiling  Running  Spell Check  Convention Check  In the above code, we have created a VisualStudio class that has to execute() method.  In the desktop-class, we have passed the ide as an argument in the code().  An ide is an object of VisualStudio class. With the help of ide,  we called the execute() method of VisualStudio class.
  • 54. How duck typing supports EAFP  The duck typing is the most appropriate style for the EAFP because we don't need to focus on the "type" of the object. We only need to take care of its behavior and capability. Let's see the following statements.  When we see a lot of if-else blocks, then it is an LBYL coding style.  But if we see a lot of try-except blocks, then it is a probability an EAFP coder.
  • 55. Name mangling in Python  In name mangling process any identifier with two leading underscore and one trailing underscore is textually replaced with _classname__identifier where classname is the name of the current class.  It means that any identifier of the form __geek (at least two leading underscores or at most one trailing underscore) is replaced with _classname__geek, where classname is the current class name with leading underscore(s) stripped.
  • 56. Example:  # Python program to demonstrate  # name mangling  class Student:  def __init__(self, name):  self.__name = name  def displayName(self):  print(self.__name)  s1 = Student(“Keerthi")  s1.displayName()  # Raises an error  print(s1.__name)
  • 57. Output  Keerthi  Traceback (most recent call last): File "/home/be691046ea08cd2db075d27186ea0493.py", line 14, in print(s1.__name) AttributeError: 'Student' object has no attribute '__name‘  In the above example, the class variable __name is not accessible outside the class. It can be accessed only within the class. Any modification of the class variable can be done only inside the class.
  • 58. Name mangling process  With the help of dir() method, we can see the name mangling process that is done to the class variable.  The name mangling process was done by the Interpreter.  The dir() method is used by passing the class object and it will return all valid attributes that belong to that object.  # Python program to demonstrate  # name mangling  class Student:  def __init__(self, name):  self.__name = name  s1 = Student("Santhosh")  print(dir(s1))
  • 59. Output  [‘_Student__name’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’]  The above output shows dir() method returning all valid attributes with the name mangling process that is done to the class variable __name. The name changed from __name to _Student__name.
  • 60. Accessing Name Mangled variables  The name mangling process helps to access the class variables from outside the class. The class variables can be accessed by adding _classname to it. The name mangling is closest to private not exactly private.  # Python program to demonstrate  # name mangling  class Student:  def __init__(self, name):  self.__name = name  s1 = Student(“keerthi")  print(s1._Student__name) output:keerthi  The above class variable is accessed by adding the _classname to it. The class variable is accessed from outside the class with the name _Student__name.
  • 61. Relationships in class  in object-oriented programming, there are three relationships between classes : dependencies 、 combination relationship ,inheritance relationship. Dependencies: passing the class name or object of one class as aparameter to another function is a dependency. class People: def __init__(self,name): self.name = name def open(self,bx): bx.open_door(self) def close(self,bx): bx.close_door(self)
  • 62. Cont..  class Refrigerator:  def __init__(self,name):  self.name = name def open_door(self,p):  print(f"{p.name} open the refrigerator ")  def close_door(self,p):  print(f"{p.name} close the refrigerator ")  r = People(" big magic ")  # People class instantiates an object r  aux = Refrigerator(" oakes ")  # Refrigerator class instantiates an object, aux r.open(aux)  # pass the aux object as a parameter to r object is used by the open method r.close(aux)  # pass the aux object as a parameter to r object is used by the close method
  • 63. combination relationship  encapsulating objects of one class into attributes of objects of another class is called composition  class Boy:  def __init__(self,name,g):  self.name = name # self = b  self.g = g # g is an object memory address that the girl class instantiates  def eat(self):  print(f"{self.name} and {self.g.age} years old, and {self.g.weight} kg, {self.g.name}py friends. we had a candlelight dinner together !") def make_keep(self): self.g.live(f"{self.g.weight} kg, {self.g.name} to {self.name} on the back ")
  • 64. Cont..  class Girl:  def __init__(self,name,age,sex,weight,*args):  self.name = name  self.age = age  self.gender = gender  self.weight = weight  self.args = args  def live(self,argv): print(f" live content :{argv}")  g = Girl(" joe never put off till tomorrow what you can get ",54," female ",220)  b = Boy(" so bo ",g) # encapsulates object g as a property b object b.make_keep()
  • 65. inheritance relationships  inheritance ( english :inheritance) is a concept in object-oriented software technology.  if a category A“ inherited from ” another category b, just take this one A referred to as “B the subcategory ”, let's call b “A the parent category ” can also be said “B it's a superclass of a ”  inheritance enables subcategories to have the various attributes and methods of the parent without having to write the same code again
  • 66. Example: without inheritance  class Human:  def __init__(self,name,age,gender):  self.name = name  self. gender = gender  self.age = age  def eat(self):  print(" eat ")  class Dog:  def __init__(self, name, age, gender):  self.name = name  self. gender = gender  self.age = age  def eat(self): print(" eat ") class Cat:  def __init__(self, name, age, gender):  self.name = name  self. gender = gender  self.age = age  def eat(self): print(" eat ")
  • 67. Example:inheritance  class Animal: # the parent class  """ animal """  live = " live “  def __init__(self, name, age, gender):  print("is __init__")  self.name = name  self. gender = gender  self.age = age  def eat(self): # self is the position parameter of the function  print(" eat ")  class Human(Animal): # a subclass  pass class  Dog(Animal): # a subclass  Pass  class Cat(Animal): # a subclass pass