Class Python
Class Python
# python-local-variable.py
def function_local(a):
a = 50
a = 100
function_local(40)
print('Value of a is ->',a)
Output:
a is -> 40
After new value within the function a is -> 50
Value of a is -> 100
global statement:
# python-global-variable.py
def function_local():
global a
a = 50
a = 100
function_local()
print('Value of a is ->',a)
Copy
Output:
a is -> 100
After new value within the function a is -> 50
Value of a is -> 50
.
def outside():
a = 10
def inside():
a = 20
print("Inside a ->", a)
inside()
print("outside a->", a)
outside()
def outside():
a = 10
def inside():
nonlocal a
a = 20
inside()
outside()
Defining a class:
class Student:
Statement-1
Statement-1
....
....
....
Statement-n
A class definition started with the keyword 'class' followed by
the name of the class and a colon.
Creating a Class:
class Student:
stu_class = 'V'
stu_roll_no = 12
stu_name = "David"
Class Objects:
class Student:
stu_class = 'V'
stu_roll_no = 12
stu_name = "David"
def messg(self):
__init__ method:
#studentdetailsinit.py
class Student:
self.c = sclass
self.r = sroll
self.n = sname
def messg(self):
Statement-1
Statement-1
....
....
....
Statement-n
class DerivedClassName(BaseClassName1, BaseClassName2,
BaseClassName3):
Statement-1
Statement-1
....
....
....
Statement-n
Example:
class CompanyMember:
self.name = name
self.designation = designation
self.age = age
def tell(self):
'''Details of an employee.'''
print('Name: ', self.name,'\nDesignation : ',self.designation, '\
nAge : ',self.age)
class FactoryStaff(CompanyMember):
self.overtime_allow = overtime_allow
CompanyMember.tell(self)
class OfficeStaff(CompanyMember):
self.marks = travelling_allow
CompanyMember.tell(self)
Now execute the class in Python Shell and see the output.
Encapsulation
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
self.__maxprice = price
c = Computer()
c.sell()
c.__maxprice = 1000
c.sell()
c.setMaxPrice(1000)
c.sell()
output :
Polymorphism
# Create instance
obj = Human()
# Call the method
obj.sayHello()
Output:
Hello
Hello Guido
Method Overriding
class Rectangle():
def __init__(self,length,breadth):
self.length = length
self.breadth = breadth
def getArea(self):
class Square(Rectangle):
def __init__(self,side):
self.side = side
Rectangle.__init__(self,side,side)
def getArea(self):
s = Square(4)
r = Rectangle(2,4)
s.getArea()
r.getArea()
output :
16 is area of square
8 is area of rectangle