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:
class A: #defining a class
pass
k = A() #creating an object
print(type(k)) #returns the type of k
Output:
<class'__main__.A'>
Example 2:
a and b are objects, parrot is a class
class parot:
# class attribute
# species is class variable
species = "bird"
# instance attribute
# name, age are instance variables
def __init__(self,name,age):
self.name = name
self.age = age
a = parot("kuhu",10)
b = parot("piku",15)
print("Species of the parrot is :", a.species)
print("Species of the parrot is : {}".format(b.species))
print("The {} name is {} and age is {} ".format(a.species,a.name, a.age))
print("The {} name is {} and age is {} ".format(b.species,b.name, b.age))
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.
class Parrot:
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
# instantiate the object
blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())
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.
# parent class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster
Example:
#!/usr/bin/python3
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
#This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
#This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
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 “ _“.
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def abc(self):
print("the max price is {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
print(c.__maxprice)
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
c.abc()
d = Computer()
d.abc()
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?