Python Classes: Class
Python Classes: Class
Since many houses can be made from the same description, we can create
many objects from a class.
class ClassName:
# class definition
class Bike:
name = ""
gear = 0
Here,
objectName = ClassName()
# create class
class Bike:
name = ""
gear = 0
Here, bike1 is the object of the class. Now, we can use this object to access
the class attributes.
Access Class Attributes Using Objects
We use the . notation to access the attributes of a class. For example,
Here, we have used bike1.name and bike1.gear to change and access the value
of name and gear attribute respectively.
Example 1: Python Class and Objects
# define a class
class Bike:
name = ""
gear = 0
Output
In the above example, we have defined the class named Bike with two
attributes: name and gear .
# define a class
class Employee:
# define an attribute
employee_id = 0
Output
In the above example, we have created two objects employee1 and employee2 of
the Employee class.
Python Methods
We can also define a function inside a Python class. A Python
Function defined inside a class is called a method.
Let's see an example,
# create a class
class Room:
length = 0.0
breadth = 0.0
Method: calculate_area()
Here, we have created an object named study_room from the Room class. We
then used the object to assign values to attributes: length and breadth .
Notice that we have also used the object to call the method inside the class,
study_room.calculate_area()
Here, we have used the . notation to call the method. Finally, the statement
inside the method is executed.
Python Constructors
Earlier we assigned a default value to a class attribute,
class Bike:
name = ""
...
# create object
bike1 = Bike()
However, we can also initialize values using the constructors. For example,
class Bike:
# constructor function
def __init__(self, name = ""):
self.name = name
bike1 = Bike()
Here, __init__() is the constructor function that is called whenever a new
object of that class is instantiated.
The constructor above initializes the value of the name attribute. We have used
the self.name to refer to the name attribute of the bike1 object.
If we use a constructor to initialize values inside a class, we need to pass the
corresponding value during the object creation of the class.
The new class that is created is known as subclass (child or derived class)
and the existing class from which the child class is derived is known
as superclass (parent or base class).
Python Inheritance Syntax
Here's the syntax of the inheritance in Python,
# define a superclass
class super_class:
# attributes and method definition
# inheritance
class sub_class(super_class):
# attributes and method of super_class
# attributes and method of sub_class
Here, we are inheriting the sub_class class from the super_class class.
Example 1: Python Inheritance
class Animal:
def eat(self):
print("I can eat")
Output
I can eat
My name is Rohu
labrador.name = "Rohu"
labrador.eat()
Here, we are using labrador (object of Dog ) to access name and eat() of
the Animal class. This is possible because the subclass inherits all attributes
and methods of the superclass.
Also, we have accessed the name attribute inside the method of the Dog class
using self .
is-a relationship
In Python, inheritance is an is-a relationship. That is, we use inheritance only
if there exists an is-a relationship between two classes. For example,
1. Car is a Vehicle
2. Apple is a Fruit
3. Cat is an Animal
Here, Car can inherit from Vehicle, Apple can inherit from Fruit, and so on.
Example 2: Inheritance in Python
class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]
def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
This class has data attributes to store the number of sides n and magnitude of
each side as a list called sides .
class Triangle(Polygon):
def __init__(self):
Polygon.__init__(self,3)
def findArea(self):
a, b, c = self.sides
# calculate the semi-perimeter
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
However, the Triangle class has a new method findArea() to find and print the
area of the triangle.
Now let's see the complete working code of the example above including
creating an object,
class Polygon:
# Initializing the number of sides
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]
class Triangle(Polygon):
# Initializing the number of sides of the triangle to 3 by
# calling the __init__ method of the Polygon class
def __init__(self):
Polygon.__init__(self,3)
def findArea(self):
a, b, c = self.sides
Output
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0
The area of the triangle is 6.00
Here, we can see that even though we did not define methods
like inputSides() or dispSides() for class Triangle separately, we were able to use
them.
If an attribute is not found in the class itself, the search continues to the base
class. This repeats recursively, if the base class is itself derived from other
classes.
However, what if the same method is present in both the superclass and
subclass?
In this case, the method in the subclass overrides the method in the
superclass. This concept is known as method overriding in Python.
def eat(self):
print("I can eat")
Output
In the above example, the same method eat() is present in both the Dog class
and the Animal class.
Now, when we call the eat() method using the object of the Dog subclass, the
method of the Dog class is called.
This is because the eat() method of the Dog subclass overrides the same
method of the Animal superclass.
The super() Method in Python Inheritance
Previously we saw that the same method in the subclass overrides the
method in the superclass.
name = ""
def eat(self):
print("I can eat")
labrador.eat()
Run Code
Output
I can eat
I like to eat bones
In the above example, the eat() method of the Dog subclass overrides the
same method of the Animal superclass.
Inside the Dog class, we have used
# call method of superclass
super().eat()
to call the eat() method of the Animal superclass from the Dog subclass.
So, when we call the eat() method using the labrador object
Both the overridden and the superclass version of the eat() method is
executed.
Uses of Inheritance
1. Since a child class can inherit all the functionalities of the parent's class,
this allows code reusability.
3. Since you can also add your own functionalities in the child class, you
can inherit only the useful functionalities and define other required
features.
Python Multiple Inheritance
A class can be derived from more than one superclass in Python. This is
called multiple inheritance.
For example, A class Bat is derived from superclasses Mammal and WingedAnimal .
Multiple Inheritance
class SuperClass1:
# features of SuperClass1
class SuperClass2:
# features of SuperClass2
Here, the MultiDerived class is derived from SuperClass1 and SuperClass2 classes.
Example: Python Multiple Inheritance
class Mammal:
def mammal_info(self):
print("Mammals can give direct birth.")
class WingedAnimal:
def winged_animal_info(self):
print("Winged animals can flap.")
b1.mammal_info()
b1.winged_animal_info()
Run Code
Output
In the above example, the Bat class is derived from two super
classes: Mammal and WingedAnimal . Notice the statements,
b1 = Bat()
b1.mammal_info()
b1.winged_animal_info()
class DerivedClass1(SuperClass):
# Derived class 1 code here
class DerivedClass2(DerivedClass1):
# Derived class 2 code here
Here, the DerivedClass1 class is derived from the SuperClass class, and
the DerivedClass2 class is derived from the DerivedClass1 class.
def super_method(self):
print("Super Class method called")
# define class that derive from SuperClass
class DerivedClass1(SuperClass):
def derived1_method(self):
print("Derived class 1 method called")
def derived2_method(self):
print("Derived class 2 method called")
Output
class SuperClass2:
def info(self):
print("Super Class 2 method called")
d1 = Derived()
d1.info()
Here, SuperClass1 and SuperClass2 both of these classes define a method info() .
So when info() is called using the d1 object of the Derived class, Python uses
the MRO to determine which method to call.
In this case, the MRO specifies that methods should be inherited from the
leftmost superclass first, so info() of SuperClass1 is called rather than that
of SuperClass2 .
Python Operator Overloading
In Python, we can change the way operators work for user-defined types.
For example, the + operator will perform arithmetic addition on two numbers,
merge two lists, or concatenate two strings.
This feature in Python that allows the same operator to have different
meaning according to the context is called operator overloading.
Python Special Functions
Class functions that begin with double underscore __ are called special
functions in Python.
The special functions are defined by the Python interpreter and used to
implement certain features or behaviors.
They are called "double underscore" functions because they have a double
underscore prefix and suffix, such as __init__() or __add__() .
Func on Descrip on
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x, self.y)
p1 = Point(1, 2)
p2 = Point(2, 3)
print(p1+p2)
# Output: (3,5)
Run Code
Addi on p1 + p2 p1.__add__(p2)
Subtrac on p1 - p2 p1.__sub__(p2)
Power p1 ** p2 p1.__pow__(p2)
Division p1 / p2 p1.__truediv__(p2)
Bitwise OR p1 | p2 p1.__or__(p2)
p1 = Person("Alice", 20)
p2 = Person("Bob", 30)
Output
True
False
Here, __lt__() overloads the < operator to compare the age attribute of two
objects.
The __lt__() method returns,
True - if the first object's age is less than the second object's age
False - if the first object's age is greater than the second object's age
Allows for code reuse by implementing one operator method and using
it for other operators.