Become a certified Python
programmer.
Created with over a decade of experience.
Certification Courses
Created with over a decade of experience and thousands of feedback.
Become a certified Python
programmer.
Try Programiz PRO!Become a certified Python
programmer.
Python Introduction
Python Fundamentals
Python Flow Control
Python Data types
Python Functions
Python Files
Python Exception Handling
Python Object & Class
Python Advanced Topics
Python Date and Time
Additional Topic
Python Object Oriented Programming
Python is a versatile programming language that supports various programming styles, including object-oriented programming (OOP) through the use ofobjects andclasses.
An object is any entity that hasattributes andbehaviors. For example, aparrot
is an object. It has
- attributes - name, age, color, etc.
- behavior - dancing, singing, etc.
Similarly, a class is a blueprint for that object.
Python Class and Object
class Parrot: # class attribute name = "" age = 0# create parrot1 objectparrot1 = Parrot()parrot1.name = "Blu"parrot1.age = 10# create another object parrot2parrot2 = Parrot()parrot2.name = "Woo"parrot2.age = 15# access attributesprint(f"{parrot1.name} is {parrot1.age} years old")print(f"{parrot2.name} is {parrot2.age} years old")
Output
Blu is 10 years oldWoo is 15 years old
In the above example, we created a class with the nameParrot with two attributes:name andage.
Then, we create instances of theParrot class. Here,parrot1 andparrot2 are references (value) to our new objects.
We then accessed and assigned different values to the instance attributes using the objects name and the.
notation.
To learn more about classes and objects, visitPython Classes and Objects
Python Inheritance
Inheritance is a way of creating a new class for using details of an existing class without modifying it.
The newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class).
Example 2: Use of Inheritance in Python
# base classclass Animal: def eat(self): print( "I can eat!") def sleep(self): print("I can sleep!")# derived classclass Dog(Animal): def bark(self): print("I can bark! Woof woof!!")# Create object of the Dog classdog1 = Dog()# Calling members of the base classdog1.eat()dog1.sleep()# Calling member of the derived classdog1.bark();
Output
I can eat!I can sleep!I can bark! Woof woof!!
Here,dog1 (the object of derived classDog) can access members of the base class Animal. It's becauseDog is inherited fromAnimal.
# Calling members of the Animal classdog1.eat()dog1.sleep()
To learn more about inheritance, visitPython Inheritance.
Python Encapsulation
Encapsulation is one of the key features of object-oriented programming. Encapsulation refers to the bundling of attributes and methods inside a single class.
It prevents outer classes from accessing and changing attributes and methods of a class. This also helps to achievedata hiding.
In Python, we denote private attributes using underscore as the prefix i.e single_
or double__
. For example,
class Computer: def __init__(self): self.__maxprice = 900 def sell(self): print("Selling Price: {}".format(self.__maxprice)) def setMaxPrice(self, price): self.__maxprice = pricec = Computer()c.sell()# change the pricec.__maxprice = 1000c.sell()# using setter functionc.setMaxPrice(1000)c.sell()
Output
Selling Price: 900Selling Price: 900Selling Price: 1000
In the above program, we defined aComputer class.
We used__init__()
method to store the maximum selling price ofComputer
. Here, notice the code
c.__maxprice = 1000
Here, we have tried to modify the value of__maxprice outside of the class. However, since__maxprice is a private variable, this modification is not seen on the output.
As shown, to change the value, we have to use a setter function i.esetMaxPrice()
which takes price as a parameter.
Polymorphism
Polymorphism is another important concept of object-oriented programming. It simply means more than one form.
That is, the same entity (method or operator or object) can perform different operations in different scenarios.
Let's see an example,
class Polygon: # method to render a shape def render(self): print("Rendering Polygon...")class Square(Polygon): # renders Square def render(self): print("Rendering Square...")class Circle(Polygon): # renders circle def render(self): print("Rendering Circle...") # create an object of Squares1 = Square()s1.render()# create an object of Circlec1 = Circle()c1.render()
Output
Rendering Square...Rendering Circle...
In the above example, we have created a superclass:Polygon and two subclasses:Square andCircle. Notice the use of therender()
method.
The main purpose of therender()
method is to render the shape. However, the process of rendering a square is different from the process of rendering a circle.
Hence, therender()
method behaves differently in different classes. Or, we can sayrender()
is polymorphic.
To learn more about polymorphism, visitPolymorphism in Python.
Key Points to Remember:
- Object-Oriented Programming makes the program easy to understand as well as efficient.
- Since the class is sharable, the code can be reused.
- Data is safe and secure with data abstraction.
- Polymorphism allows the same interface for different objects, so programmers can write efficient code.
Also Read:
Our premium learning platform, created with over a decade of experience and thousands of feedbacks.
Learn and improve your coding skills like never before.
Try Programiz PRO- Interactive Courses
- Certificates
- AI Help
- 2000+ Challenges