Advance Python Program Unit I Continuation -OOPS
Advance Python Program Unit I Continuation -OOPS
Raakesh Kumar
19. Opps Concept in
Python
3
▪ Class
▪ class is a user-defined data type that
contains both the data itself and the
methods that may be used to manipulate
it.
▪ Classes serve as a template to create
objects.
▪ A class is a prototype of a building.
▪ A building contains all the details about the
floor, rooms, doors, windows, etc.
▪ we can make as many buildings as we
want, based on these details.
5
▪ Class ▪ Syntax
▪ The class can be defined as a
collection of objects. class ClassName:
▪ It is a logical entity that has some
<statement-1>
specific attributes and methods.
.
▪ For example: if you have an
employee class, then it should .
contain an attribute and method, <statement-N>
▪ i.e. an email id, name, age, salary,
etc.
7
▪ Example: ▪ Output:
class car: ▪ Toyota 2016
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
9
▪ Object ▪ Method
▪ In the above example, we have ▪ The method is a function that is
created the class named car, associated with an object. In Python, a
and it has two attributes method is not unique to class instances.
modelname and year. Any object type can have methods.
▪ We have created a c1 object to
access the class attribute.
▪ The c1 object will allocate
memory for these values.
10
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
▪ Syntax d.bark()
d.speak()
class derived-class(base class):
<class-suite> Output:
dog barking Animal Speaking
20
def Divide(self,a,b):
return a/b;
24
c.setMaxPrice(1000)
c.sell()
26
class Polygon:
▪ Polymorphism # method to render a shape
▪ Polymorphism contains two words def render(self):
"poly" and "morphs". print("Rendering Polygon...")
▪ Poly means many, and morph means class Square(Polygon):
shape. # renders Square
▪ By polymorphism, we understand that def render(self):
one task can be performed in different print("Rendering Square...")
ways. class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")
27
Method Overriding
▪ Example:
▪ When the parent class method is ▪ class Animal:
defined in the child class with some
specific implementation, then the
▪ def speak(self):
concept is called method overriding. ▪ print("speaking")
▪ We may need to perform method ▪ class Dog(Animal):
overriding in the scenario where the ▪ def speak(self):
different definition of a parent class
▪ print("Barking")
method is needed in the child class.
▪ d = Dog()
▪ d.speak()
▪ Output: Barking
29
Assertion
“
Code1
The End
”
34
Hello!
I am Raakesh Kumar
I am here because I love
Python.
You can reach me at
info@ritepros.com
or
Group whatsapp.