OBJECT ORIENTED PROGRAMMING IN PYTHON
Creating Classes
5
��Find out the cost of a rectangular field with breadth(b=120), length(l=160). It costs x (2000) rupees per 1 square unit
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
# breadth = 120 units, length = 160 units, 1 sq unit cost = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))
Example
8
Creating Objects
9
10
Access Specifiers
Type | Naming |
private | __name (double underscore) |
protected | _name |
public | name |
Class Inheritance
15
Example:
16
Multilevel inheritance
class sam1:
def get(self):
print("base1")
self.a=int(input());
class sam2:
def disp(self):
print("base2")
self.b=int(input());
class sam3(sam1,sam2):
def display(self):
print(self.a,self.b);
s=sam3();
s.get();
s.disp();
s.display();
Overriding Methods
18
Static Method
class C():
@staticmethod
def fun(arg1, arg2, ...):
...
returns:
Static method Example
class sample:
e=10;
def get(self):
self.a=int(input("Enter No1"));
@staticmethod
def disp():
print("Static method",sample.e);
s=sample();
s.get();
sample.disp();
s.disp();
Class Method
A class method receives the class as implicit first argument, just like an instance method receives the instance�Syntax:
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
Class Method
class Kls(object):
no_inst = 0
def __init__(self):
Kls.no_inst = Kls.no_inst + 1
@classmethod
def get_no_of_instance(cls):
return cls.no_inst
ik1 = Kls()
ik2 = Kls()
print (ik1.get_no_of_instance())
print (Kls.get_no_of_instance())
Class method vs Static Method
Thank you