Declaring a class
We define a class in Python using the class keyword.To define a class called Main we use the following:
class Main: def __init__(self): self.tempVar= 1 def SetValue(self,value): self.EmpId=value def GetValue(self): print("EmpId=%s"%(self.EmpId))
There are few important points to be noted in the above code:
1.Class is defined using the class keyword.Here the name of the class is Main.
2.Class initialization happens in a method called __init__.It is similar to class constructor in other languages.
3.Methods are defined in a similar way as normal functions using the def statement followed by method name.
4.self is the parameter defined in the method above.It refers to the class object using which the method is callled.So if you have two different objects a and b then self will refer to a when called using the object a and it will refer to b when called using the object b.
We can declare objects of the above class as:
obj1=Main() obj1.SetValue(1) obj1.GetValue() obj2=Main() obj2.SetValue(2) obj2.GetValue()
Inheritance
A class can inherit the attributes from another class.In the following example we are defining a class called Inherited which inherits its behaviour from class Main.
class Inherited(Main): def Message(self): print("Hello from Inherited") print("EmpId=%d"%(self.tempVar))
Following are the main points in the class declaration above:
1.A inherited class is declared just like a normal class.But after the nanme of the class we pass parent class name in brackets.
2.The inherited class has access to the variables of the parent class.In the above sample we are accessing the variable called tempVar in the derived class.
Multilevel Inheritance
You can implement multilevel inheritance as:
class FirstClass: pass class SecondClass(FirstClass): pass class ThirdClass(SecondClass): pass
Calling parent class constructor
The constructor defined in the child class is called when the object of child class is created.So if the child class defines the following constructor,then only this constructor will be called and the parent class constructor will not be called.
def__init__(self): Main.__init__(self) print("child constructor")
If you want to call the parent class constructor then you can call it as:
class Main: def__init__(self): self.tempVar=1 print("base constructor")
Calling Super class methods
We can call the super class methods from child class using the super method as:
super().parentMethodName(args)
Leave a Reply