Declaring a class
We define a class in Python using the class keyword.To define a class called Main we use the following:
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 differen 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:
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.
print("Hello from Inherited")
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.
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.
If you want to call the parent class constructor then you can call it as:
Calling Super class methods
We can call the super class methods from child class using the super method as: