Class and Objects
Class and Objects
Defining a Class
• A Python class uses variables to store data fields and defines
methods to perform actions.
• Additionally, a class provides a special type method, known as
initializer, which is invoked to create a new object. An initializer
can perform any action, but initializer is designed to perform
initializing actions, such as creating the data fields of objects.
• Class can be defined by,
Creating an Object
• Once class is defined, variable/instance can be
created by
• Example
Creating an Object
• Once class is defined, variable/instance can be
created by
• Example
Creating an Object
• Once class is defined, variable/instance can be
created by
• Example
Creating an Object
• Once class is defined, variable/instance can be
created by
• Example
The __init__() method(Constructor)
• All classes have a function called __init__(), which is always
executed when the class is being initiated.
• The __init__() method is automatically invoked when object is
created.
• Used to initialize the variables of the class object
• It is declared as,
def __init__(self,[args…])
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Class Attributes
• Instance variables: The instance variables are attributes attached to
an instance of a class. We define instance variables in the constructor
( the __init__() method of a class).
• Instance/Object variables are not shared between objects
• If any change is made to one object variable that will not reflect to
other objects
• Class Variables: A class variable is a variable that is declared inside of
class, but outside of any instance method or __init__() method.
• Class variables are common to all the objects
• If class has n objects, there will be n separate copies of variables are
created
Class Variables
class Shark:
animal_type = "fish"
location = "ocean"
followers = 5
new_shark = Shark()
print(new_shark.animal_type)
print(new_shark.location)
print(new_shark.followers)
Instance variables
• Unlike class variables, instance variables are defined
within methods.
• In the Shark class example below, name and age are
instance variables:
class Shark:
def __init__(self, name, age):
self.name = name
self.age = age
new_shark = Shark("Sammy", 5) # Instance creation
class Student:
# class variables
school_name = 'ABC School'
# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age
s1 = Student("Harry", 12)
# access instance variables
print('Student:', s1.name, s1.age)
# access class variable
print('School name:', Student.school_name)
# Modify instance variables
s1.name = 'Jessa'
s1.age = 14
print('Student:', s1.name, s1.age)
# Modify class variables
Student.school_name = 'XYZ School'
print('School name:', Student.school_name)
non-parameterized constructor
class Company:
# no-argument constructor
def __init__(self):
self.name = "PYnative"
self.address = "ABC Street"
# display object
def show(self):
print(self.name, self.age, self.salary)
• Private members are accessible only within the class, and we can’t access them directly from
the class objects.
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
self.fare = fare
bus= Vehicle(20)
car= Vehicle(30)
total_fare=bus+ car
print(total_fare)
Error has occurred, this is because python has no idea how to add two objects together. Here Vehicle
is the object.
Operator Overloading in Python
• changing the default behavior of an operator depending on the
operands (values) that we use
• same operator can be used for multiple purposes
• + operator will perform an arithmetic addition operation when used
with numbers & perform concatenation when used with strings
Example
print(100 + 200)
# concatenate two strings
print('Jess' + 'Roy')
# merger two list
print([10, 20, 30] + ['jessa', 'emma', 'kelly'])
Operator overloading
• operator + is used to add two integers as well as join two strings and
merge two lists.
• To add two objects with binary ‘+’ operator it throws an error, because
compiler don’t know how to add two objects.
• Define a method for an operator and that process is called operator
overloading
• Python provides some special function or magic function that is
automatically invoked when it is associated with that particular operator.
• when we use + operator, the magic method add is automatically
invoked in which the operation for + operator is defined
__add__ operator
bus= Vehicle(20)
car= Vehicle(30)
total_fare=bus+ car
print(total_fare)
Python magic methods or special functions
for operator overloading
Operator Magic Method
+ __add__(self, other)
– __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
>> __rshift__(self, other)
<< __lshift__(self, other)
& __and__(self, other)
| __or__(self, other)
^ __xor__(self, other)
Comparison Operators:
Operator Magic Method
< __lt__(self, other)
> __gt__(self, other)
<= __le__(self, other)
>= __ge__(self, other)
== __eq__(self, other)
!= __ne__(self, other)
Polymorphism
Operator overloading-Compare two integers.
Create a class 'compare' that perform comparing two integers
creating an object obj1 and obj2 for class compare(For passing
the argument)
After creating object obj1 and obj2, compare both objects.
(obj1>obj2)
Example:
If A>B the print True else print False.
Polymorphism
class compare:
def __init__(self, a):
self.a = a
def __gt__(self, other):
if(self.a>other.a):
return True
else:
return False
A = int(input())
B = int(input())
obj1=compare(A)
obj2=compare(B)
print(A>B)
Operator overloading-Addition of two complex numbers:
Create a class 'Complex' to add two complex numbers. The complex number contains the real
parts and the imaginary parts.
Create two objects c1 and c2.
c1 passes the first complex number. c2 passes the second complex number.
Create a method overloading for the '+' operator, so that it should perform complex numbers
addition.
After creating objects c1 and c2, c1+c2 should display the addition of 2 complex numbers.
Refer sample input and sample output for formatting specification
I/P
2
3
4
5
O/P
(6+8j)
class Complex:
# defining init method for class
def __init__(self, r, i):
self.real = r
self.img = i
# overloading the add operator using special function
def __add__(self, sec):
r = self.real + sec.real
i = self.img + sec.img
return complex(r,i)
# string function to print object of Complex class
def __str__(self):
return str(self.real)+' + '+str(self.img)+'i'
a=int(input())
b=int(input())
c=int(input())
d=int(input())
c1 = Complex(a,b)
c2 = Complex(c,d)
print(c1+c2)
Polymorphism in user-defined methods
from math
import pi
class square:
def __init__(self, length):
self.l = length
def perimeter(self):
return 4 * (self.l)
def area(self):
return self.l * self.l
class Circle:
def __init__(self, radius):
self.r = radius
def perimeter(self):
return 2 * pi * self.r
def area(self):
return pi * self.r * * 2
# Initialize the classes
sqr = square(10)
c1 = Circle(4)
print("Perimeter computed for square: ", sqr.perimeter())
print("Area computed for square: ", sqr.area())
print("Perimeter computed for Circle: ", c1.perimeter())
Method Overloading
• The process of calling the same method with different parameters is known as method
overloading
• Basically python does not support method overloading, but there are several ways to
achieve method overloading.
• Though method overloading can be achieved, the last defined methods can only be usable.
• Otherwise TypeError will be raised if you overload the method
def addition(a, b):
c=a+b
print(c)
def addition(a, b, c):
d=a+b+c
print(d)
addition(4, 5)
addition(3, 7, 5)
Inheritance
• process of inheriting the properties of the parent class into a child
class is called inheritance
• The existing class is called a base class or parent class and the new
class is called a subclass or child class or derived class.
• main purpose of inheritance is the reusability of code
• existing class is used to create a new class instead of creating it from
scratch.
Single Inheritance
• a child class inherits from a single-parent class. Here is one child class and one parent class.
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Create object of Car
car = Car()
# access Vehicle's info using car object
car.Vehicle_info()
car.car_info()
Multiple Inheritance
• one child class can inherit from multiple parent classes
class Person:
def person_info(self, name, age):
print('Inside Person class')
print('Name:', name, 'Age:', age)
# Parent class 2
class Company:
def company_info(self, company_name, location):
print('Inside Company class')
print('Name:', company_name, 'location:', location)
# Child class
class Employee(Person, Company):
def Employee_info(self, salary, skill):
print('Inside Employee class')
print('Salary:', salary, 'Skill:', skill)
# Create object of Employee
emp = Employee()
# access data
emp.person_info('Jessa', 28)
emp.company_info('Google', 'Atlanta')
emp.Employee_info(12000, 'Machine Learning')
Multilevel inheritance
• class inherits from a child class or derived class.
• A is the superclass, B is the child class of A, C is the child class of B
• chain of classes is called multilevel inheritance.
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Child class
class SportsCar(Car):
def sports_car_info(self):
print('Inside SportsCar class')
# Create object of SportsCar
s_car = SportsCar()
# access Vehicle's and Car info using SportsCar object
s_car.Vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Hierarchical Inheritance
• more than one child class is derived from a single parent class
class Vehicle:
def info(self):
print("This is Vehicle")
class Car(Vehicle):
def car_info(self, name):
print("Car name is:", name)
class Truck(Vehicle):
def truck_info(self, name):
print("Truck name is:", name)
obj1 = Car()
obj1.info()
obj1.car_info('BMW')
obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')
Hybrid Inheritance
• multiple types or a combination of different inheritance is called hybrid inheritance.
class Vehicle:
def vehicle_info(self):
print("Inside Vehicle class")
class Car(Vehicle):
def car_info(self):
print("Inside Car class")
class Truck(Vehicle):
def truck_info(self):
print("Inside Truck class")
# Sports Car can inherits properties of Vehicle and Car
class SportsCar(Car, Vehicle):
def sports_car_info(self):
print("Inside SportsCar class")
# create object
s_car = SportsCar()
s_car.vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Write a program to create the following:
Class Name: Pow, parameters: a, b (integers), Method: display (to print the value of a to the power
of b)
Class Name: Pow1 (child class of Pow).parameters: inherited from Pow.Method: display1 (to print
the value of a*b).Create an object for Pow1. Using that object, call display and display1.
class Pow:
def __init__(self,a,b):
self.a = a
self.b = b
def display(self):
print(self.a**self.b)
class Pow1(Pow):
def display1(self):
print(self.a*self.b)
a = int(input())
b =int(input())
obj=Pow1(a,b)
Polymorphism With Inheritance
• Inheritance child class inherits the attributes and methods of a parent
class.
• The existing class is called a base class or parent class, and the new
class is called a subclass or child class or derived class
• Using method overriding polymorphism allows us to defines
methods in the child class that have the same name as the methods in
the parent class.
• This process of re-implementing the inherited method in the child
class is known as Method Overriding.
class Vehicle: # Car Object
def __init__(self, name, color, price):
self.name = name
car = Car('Car x1', 'Red', 20000)
self.color = color car.show()
self.price = price # calls methods from Car class
def show(self):
print('Details:', self.name, self.color, self.price) car.max_speed()
def max_speed(self): car.change_gear()
print('Vehicle max speed is 150')
# Vehicle Object
def change_gear(self):
print('Vehicle change 6 gear') vehicle = Vehicle('Truck x1', 'white',
# inherit from vehicle class 75000)
class Car(Vehicle): vehicle.show()
def max_speed(self):
print('Car max speed is 240')
# calls method from a Vehicle class
def change_gear(self): vehicle.max_speed()
print('Car change 7 gear') vehicle.change_gear()
Association
• relationship between two or more objects where all objects have
their own lifecycle and there is no owner.
• Each object has its own life cycle
• For example students and teachers, both classes are associated with
each other
• Multiple students can associate with a single teacher and a
single student can associate with multiple teacher
Aggregation:
• It's a unidirectional association.
• When an object can access another object then that relationship is called aggregation
• Aggregation is a week form of composition.
• relationship between the Department and Teacher.Teacher may belong to multiple departments, if we delete a
Department, Teacher Object will not destroy.
class Salary:
def __init__(self, pay):
self.pay = pay
def get_total(self):
return (self.pay*12)
class Employee:
def __init__(self, pay, bonus):
self.pay = pay
self.bonus = bonus
def annual_salary(self):
return "Total: " + str(self.pay.get_total() + self.bonus)
obj_sal = Salary(600)
class Heart:
def __init__(self, heartValves):
self.heartValves = heartValves
def display(self):
return self.heartValves
class Person:
def __init__(self, fname, lname, address,
heartValves):
self.fname = fname
self.lname = lname
self.address = address
self.heartValves = heartValves # Aggregation
def display(self):
print("First Name: ", self.fname)
print("Last Name: ", self.lname)
print("Address: ", self.address)
print("No of Healthy Valves: ", hv.display())
hv = Heart(4)
p = Person("Adam", "Lee", "555 wso blvd", hv)
p.display()