Local Variables:
# python-local-variable.py
def function_local(a):
print('a is -> ',a)
a = 50
print('After new value within the function a is -> ',a)
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
print('a is -> ',a)
a = 50
print('After new value within the function a is -> ',a)
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
print("The value of a in inside() function - ", a)
inside()
print("The value of a in outside() function - ", a)
outside()
Defining a class:
In object oriented programming classes and objects are the
main features. A class creates a new data type and objects are
instances of a class which follows the definition given inside
the class. Here is a simple form of class definition.
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.
The statements within a class definition may be function
definitions, data members or other statements.
When a class definition is entered, a new namespace is
created, and used as the local scope.
Creating a Class:
Here we create a simple class using class keyword followed
by the class name (Student) which follows an indented block
of segments (student class, roll no., name).
#studentdetails.py
class Student:
stu_class = 'V'
stu_roll_no = 12
stu_name = "David"
Class Objects:
There are two kind of operations class objects supports :
attribute references and instantiation. Attribute references use
the standard syntax, obj.name for all attribute references in
Python. Therefore if the class definition (add a method in
previous example) look like this
#studentdetails1.py
class Student:
"""A simple example class"""
stu_class = 'V'
stu_roll_no = 12
stu_name = "David"
def messg(self):
return 'New Session will start soon.'
__doc__ is also a valid attribute which returns the docstring of
the class.
__init__ method:
#studentdetailsinit.py
class Student:
"""A simple example class"""
def __init__(self, sclass, sroll, sname):
self.c = sclass
self.r = sroll
self.n = sname
def messg(self):
return 'New Session will start soon.'
Inheritance:
class DerivedClassName(BaseClassName):
Statement-1
Statement-1
....
....
....
Statement-n
class DerivedClassName(BaseClassName1, BaseClassName2,
BaseClassName3):
Statement-1
Statement-1
....
....
....
Statement-n
Example:
In a company Factory, staff and Office staff have certain
common properties - all have a name, designation, age etc.
Thus they can be grouped under a class called
CompanyMember. Apart from sharing those common features,
each subclass has its own characteristic - FactoryStaff gets
overtime allowance while OfficeStaff gets traveling allowance
for an office job. The derived classes ( FactoryStaff &
OfficeStaff) has its own characteristic and, in addition, they
inherit the properties of the base class (CompanyMember). See
the example code.
# python-inheritance.py
class CompanyMember:
'''Represents Company Member.'''
def __init__(self, name, designation, age):
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):
'''Represents a Factory Staff.'''
def __init__(self, name, designation, age, overtime_allow):
CompanyMember.__init__(self, name, designation, age)
self.overtime_allow = overtime_allow
CompanyMember.tell(self)
print('Overtime Allowance : ',self.overtime_allow)
class OfficeStaff(CompanyMember):
'''Represents a Office Staff.'''
def __init__(self, name, designation, age, travelling_allow):
CompanyMember.__init__(self, name, designation, age)
self.marks = travelling_allow
CompanyMember.tell(self)
print('Traveling Allowance : ',self.travelling_allow)
Now execute the class in Python Shell and see the output.
Encapsulation
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
output :
Selling Price: 900
Selling Price: 900
Selling Price: 1000
Polymorphism
Method overloading example
class Human:
def sayHello(self, name=None):
if name is not None:
print 'Hello ' + name
else:
print 'Hello '
# Create instance
obj = Human()
# Call the method
obj.sayHello()
# Call the method with a parameter
obj.sayHello('Guido')
Output:
Hello
Hello Guido
Method Overriding
class Rectangle():
def __init__(self,length,breadth):
self.length = length
self.breadth = breadth
def getArea(self):
print(self.length*self.breadth," is area of rectangle")
class Square(Rectangle):
def __init__(self,side):
self.side = side
Rectangle.__init__(self,side,side)
def getArea(self):
print(self.side*self.side," is area of square")
s = Square(4)
r = Rectangle(2,4)
s.getArea()
r.getArea()
output :
16 is area of square
8 is area of rectangle