0% found this document useful (0 votes)
6 views11 pages

Class and Inheritance in Python

The document explains class methods, instance methods, and static methods in Python, highlighting their definitions, usage, and differences. It also covers inheritance types, polymorphism, method overriding, and operator overloading, providing examples for each concept. Overall, it serves as a comprehensive guide to object-oriented programming principles in Python.

Uploaded by

rutikhonde274
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

Class and Inheritance in Python

The document explains class methods, instance methods, and static methods in Python, highlighting their definitions, usage, and differences. It also covers inheritance types, polymorphism, method overriding, and operator overloading, providing examples for each concept. Overall, it serves as a comprehensive guide to object-oriented programming principles in Python.

Uploaded by

rutikhonde274
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

class methods

===================================================================================
=
A method defined inside class with first parameter "cls" is called class method
this method is bind with class name and can be called or invoked without creating
object.
class methods are used to operate class variables
class methods cannot access instance members

class class-name:
@classmethod
def class-method-name(cls,...):
statement-1
statement-1
it allows accessing only class level members

def instance-method-name(self,...):
instance members
instance variables
instance method

Example:
class Alpha:
def m1(self):
print("Instance method")
@classmethod
def m2(cls):
print("class method")

Alpha.m2()
obj1=Alpha()
obj1.m1()
==========================================================================
class Customer:
__min_bal=5000 # C.L.V
def __init__(self,a,c,b):
self.__accno=a # I.V
self.__cname=c # I.V
self.__balance=b # I.V
def deposit(self,t):
self.__balance+=t
def withdraw(self,t):
if self.__balance-Customer.__min_bal>t:
self.__balance-=t
else:
print("Insuff balance")
def print_account(self):
print(self.__accno,self.__cname,self.__balance)
@classmethod
def print_min_balance(cls):
print(f'min bal {cls.__min_bal}')

Customer.print_min_balance()
cust1=Customer(1,"suresh",50000)
cust1.print_account()
[Link](10000)
cust1.print_account()
[Link](20000)
cust1.print_account()
==============================================================================
# Count of objects

class Product:
count=0 # class level variable
def __init__(self,pn,p):
self.__pname=pn
self.__price=p
[Link]+=1
@classmethod
def find_count(cls):
return [Link]

print(Product.find_count())
prod1=Product('mouse',100)
prod2=Product('keyboard',2000)
print(Product.find_count())
===================================================================================
=
What is difference between instance method and class method?
===================================================================================
=
instance method class method

1. A method defined inside class with first parameter "self" is called instanece
method
1. A method defined inside class with first parameter "cls" and
decorated with @class method

2. instance method is bind with object name (OR) it must be called with object name
(OR) it required create object to call or invoke
2. class method is bind with class name can be called without creating
object

3. instance method is able access instance variables and class variables


3. class method is able access only class members but not instance
members.
==============================================================================
static method
=================================================================================
A method defined inside class with @staticmethod decorator is called static method
these are individual methods and used to global operations

Syntax:
class class-name:
@staticmethod
def method-name(param,param,..):
statement-1
statement-2
====================================================================
class Math:
@staticmethod
def power(n,p):
return n**p
@staticmethod
def isprime(n):
c=0
for i in range(1,n+1):
if n%i==0:
c=c+1
return c==2

print([Link](5,2))
print([Link](5))

===============================================================================
class is an implemenation of encapsulation, it is encapsulated with
variables --> instance variables, class variables
methods --> instance methods, class methods, static method

===============================================================================
Inheritance
==================================================================================

Inheritance is process of acquiring the properties and behavior of one class inside
another class
Inheritance is process of grouping all the calsses which share common properties
and behavior

Inheriance provides
1. Reusability
2. Extensibility

Inheritance allows build new class or datatype based on existing class or data type
based on reusability or organization of class, inheritance is calssified into
different categories

1. single level inheritance


2. multi level inheritance
3. multiple inheritance
4. hybrid inheritance
5. hierarchical inheritance
===============================================================================
class sub-class-name(super-class,super-class,...):
variables
methods

===================================================================================
=

1. Methods of super class are automatically inherited with sub class

class A:
def m1(self):
print("m1 of A")
def m2(self):
print("m2 of B")

class B(A):
pass
obj1=B()
obj1.m1()
obj1.m2()
============================================================================
class A:
def m1(self):
print("m1 of A")
def m2(self):
print("m2 of A")

class B(A):
def m3(self):
print("m3 of B")

obj1=B()
obj1.m1()
obj1.m2()
obj1.m3()

==========================================================================
variables of base class are not inherited automatically derived class
==========================================================================
class A:
def __init__(self):
self.x=100
self.y=200

class B(A):
pass

objb=B()
print(objb.x)
print(objb.y)
-----------------------------------------------------------------------------
class A:
def __init__(self):
self.x=100
self.y=200

class B(A):
def __init__(self):
super().__init__()
self.p=300
self.q=400

objb=B()
print(objb.x)
print(objb.y)
print(objb.p)
print(objb.q)

============================================================================
# single level inheritance
# in this inheritance there is one base and derived class

class Person:
def __init__(self):
self.__name=None
def set_name(self,n):
self.__name=n
def get_name(self):
return self.__name

class Customer(Person):
def __init__(self):
super().__init__()
self.__address=None
def set_add(self,a):
self.__address=a
def get_add(self):
return self.__address

cust1=Customer()
cust1.set_name("kishore")
cust1.set_add("pune")
print(cust1.get_name())
print(cust1.get_add())

=============================================================================
# Multi level inheritance
# if class is derived from another derived class it is called multilevel
inheritance
class Person:
def __init__(self):
self.__name=None
def set_name(self,n):
self.__name=n
def get_name(self):
return self.__name

class Employee(Person):
def __init__(self):
super().__init__()
self.__job=None
def set_job(self,j):
self.__job=j
def get_job(self):
return self.__job

class SalariedEmployee(Employee):
def __init__(self):
super().__init__()
self.__salary=None

def set_salary(self,s):
self.__salary=s
def get_salary(self):
return self.__salary

emp1=SalariedEmployee()
emp1.set_salary(50000)
emp1.set_name('kishore')
emp1.set_job('se')
-----------------------------------------------------------------------------
# Multiple Inhertaince
# if class derived from more than one base class it is called multiple inheritance
class A:
def __init__(self):
self.__x=100
def get_x(self):
return self.__x

class B:
def __init__(self):
self.__y=200
def get_y(self):
return self.__y

class C(A,B):
def __init__(self):
super().__init__()
B.__init__(self)
self.__z=300
def get_z(self):
return self.__z

objc=C()
print(objc.get_x())
print(objc.get_y())
print(objc.get_z())
-------------------------------------------------------------------------------
# hierarchical inheritance
# more tha one class derived from same base class, it is called hierarchical
inheritance

class Person:
def __init__(self):
self.__name=None
def set_name(self,n):
self.__name=n
def get_name(self):
return self.__name

class Student(Person):
def __init__(self):
super().__init__()
self.__rollno=None
def set_rollno(self,r):
self.__rollno=r
def get_rollno(self):
return self.__rollno
class Lecturer(Person):
def __init__(self):
super().__init__()
self.__subject=None
def set_sub(self,s):
self.__subject=s
def get_sub(self):
return self.__subject
stud1=Student()
stud1.set_name('suresh')
stud1.set_rollno(1)
print(stud1.get_name(),stud1.get_rollno())
lect=Lecturer()
lect.set_name("ramesh")
lect.set_sub("python")
print(lect.get_name(),lect.get_sub())
==============================================================================
Polymorphism
===============================================================================
"Poly" means many and "morphism" is forms
defining one thing in many forms is called polymorphism
polymorphism provides reusability and extensibility
python supports two types of polymorphisms

1. method overriding
2. operator overloading
=================================================================================
What is method overriding?
defining method in derived class with sanme and number of parameters of method
existing in base class or super class is called method overriding

method overring allows to modify or extend functionality of base class method


within derived class.
============================================================================
class Father:
def eat(self): # overriden method
print("eat veg")

class Son(Father):
def eat(self): # Overring method
print("eat non veg")

s1=Son()
[Link]()

=============================================================================
class Employee:
def __init__(self):
self.__empno=None
self.__ename=None
def read(self):
self.__empno=int(input("EmployeeNo :"))
self.__ename=input("EmployeeName :")
def print_info(self):
print(f'{self.__empno},{self.__ename}')

class SalEmp(Employee):
def __init__(self):
super().__init__()
self.__salary=None
def read(self): # overriding method
super().read()
self.__salary=float(input("Salary :"))
def print_info(self):
super().print_info()
print(f'{self.__salary}')
emp1=SalEmp()
[Link]()
emp1.print_info()
===========================================================================
Operator Overloading
===============================================================================
Operator overloading allows to define an operation using operator.
existing operators works on predefined data types but not on user defined datatype.
to operate on user defined data type we need use operator overloading
for every operator python provides a magic method (which is prefix and suffix with
__).

Operator Method
+ __add__
- __sub__
* __mul__
/ __floatdiv__
// __floordiv__
==============================================================================
class Complex:
def __init__(self,r=0,i=0):
self.__real=r
self.__img=i
def __add__(self,other): # Operator overloading
r=Complex()
r.__real=self.__real+other.__real
r.__img=self.__img+other.__img
return r
def __sub__(self,other):
r=Complex() # Operator Overloading
r.__real=self.__real-other.__real
r.__img=self.__img-other.__img
return r

def print_complex(self):
print(f'{self.__real},{self.__img}')

c1=Complex(1.2,1)
c2=Complex(1.3,2.5)
c3=c1+c2
c1.print_complex()
c2.print_complex()
c3.print_complex()
c3=c1-c2
c3.print_complex()
==================================================================================

You might also like