Python Classes and Objects
Python Classes and Objects
Python Classes and Objects
Python Inheritance
Python is a versatile programming
language that supports various
Inheritance is a way of creating a new
programming styles, including object-
oriented programming (OOP) through the class for using details of an existing class
use of objects and classes. without modifying it.
An object is any entity that has attributes The newly formed class is a derived class
and behaviors. For example, a parrot is an (or child class). Similarly, the existing
object. It has
class is a base class (or parent class).
• attributes - name, age, color, etc.
• behavior - dancing, singing, etc.
Example 2: Use of Inheritance in
Python
Python Class and Object
# base class
class Parrot: class Animal:
Output
Rendering Square...
Selling Price: 900 Rendering Circle...
Selling Price: 900
Selling Price: 1000
In the above example, we have created a
In the above program, we defined superclass: Polygon and two
a Computer class.
subclasses: Square and Circle . Notice the
We used __init__() method to store the
use of the render() method.
maximum selling price of Computer . Here,
notice the code The main purpose of the render() method is
to render the shape. However, the process
c.__maxprice = 1000
of rendering a square is different from the
Here, we have tried to modify the value
process of rendering a circle.
of __maxprice outside of the class. However,
since __maxprice is a private variable, this Hence, the render() method behaves
modification is not seen on the output. differently in different classes. Or, we can
As shown, to change the value, we have to
say render() is polymorphic.
use a setter function i.e setMaxPrice() which
takes price as a parameter.
Python Classes and Objects
Create Object
All classes have a function called Objects can also contain methods.
__init__(), which is always executed when Methods in objects are functions that
the class is being initiated. belong to the object.
Use the __init__() function to assign Let us create a method in the Person
values to object properties, or other class:
operations that are necessary to do when
the object is being created: Example
The self parameter is a reference to the class definitions cannot be empty, but if
current instance of the class, and is used you for some reason have
to access variables that belongs to the a class definition with no content, put in
class. the pass statement to avoid getting an
error.
It does not have to be named self , you can
call it whatever you like, but it has to be Example
the first parameter of any function in the
class:
Example
Use the
words mysillyobject and abc instead
of self:
Example
Example
Delete Objects
Example