Classes & Objects
What are classes and objects in Python?
Python is an object oriented programming language. Unlike procedure oriented programming, where the main emphasis is on functions, object oriented programming stress on objects.
Object is simply a collection of data (variables) and methods (functions) that act on those data. And, class is a blueprint for the object.
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.
As, many houses can be made from a description, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.
Example 1:
Output:
<class'__main__.A'>
Example 2:
a and b are objects, parrot is a class
Species of the parrot is : bird
Species of the parrot is : bird
The bird name is kuhu and age is 10
The bird name is piku and age is 15
Methods:
Methods are functions defined inside the body of a class. They are used to define the behaviours of an object.
Blu sings 'Happy'
Blu is now dancing
Inheritance:
Inheritance is a way of creating new class for using details of 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).
In the below program, we created two classes i.e. Bird (parent class) and Penguin (child class).
The child class inherits the functions of parent class.We can see this from swim() method.
Again, the child class modified the behavior of parent class. We can see this from whoisThis() method.
Furthermore, we extend the functions of parent class, by creating a new run() method.
Additionally, we use super() function before init() method. This is because we want to pull the content of init() method from the parent class into the child class.
Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster
Example:
Output:
Name : Zara , Salary: 2000
Name : Manni , Salary: 5000
Total Employee 2
Encapsulation (Data Hiding):
Using OOP in Python, we can restrict access to methods and variables. This prevent data from direct modification which is called encapsulation. In Python, we denote private attribute using underscore as prefix i.e single “ “ or double “ _“.
Selling Price: 900
1000
Selling Price: 900
Selling Price: 1000
the max price is 1000
the max price is 900
In the above program, we defined a class Computer. We use __init__()
method to store the maximum selling price of computer. We tried to modify the price. However, we can’t change it because Python treats the __maxprice as private attributes. To change the value, we used a setter function i.e setMaxPrice()
which takes price as parameter.
Last updated
Was this helpful?