Python
Python Classes
Basic Class: Contain both data and methods. “Self” keyword refers to current instance of class and should be the first parameter of function
class cls:
x=10
def fn(self,y):
return y*y
p = cls()
print(p.x)
q=p.fn(5)
print(q)
Output:
10
25
Constructor: used for instantiation of object and assign values. The constructor in python is __init__()
class cls:
x=0
y=0
z=0
def __init__(self,x,y):
self.x=x
self.y=y
def fn(self):
self.z=self.x+self.y
return self.z
p=cls(20,30)
print(p.fn())
Output:
50
Inheritance: It is the ability of one class(child class) to derive properties and methods from another class(Parent class)
In the following example parent class property and method has been accessed by child class object
class Parentcls:
x=10
def fn(self):
print(“This is in parent class”)
class Childcls(Parentcls):
pass
p=Childcls()
print(p.x)
print(p.fn())
Output:
10
This is in parent class
Multiple Inheritance: A class is derived from more than one Parent class
In the following example the child class derived x from Parentcls1 and fn() from Parentcls2
class Parentcls1:
x=10
class Parentcls2:
def fn(self):
print(“This is in parent class 2”)
class Childcls(Parentcls1,Parentcls2):
pass
p=Childcls()
print(p.x)
print(p.fn())
Output:
10
This is in parent class 2