In this tutorial let us create a python class and then create the child class of that main class.
Create a Python class that will multiply two numbers.
class Multiply: def __init__(self, parameter1, parameter2): self.parameter1 = parameter1 self.parameter2 = parameter2 def multiplying(self): return self.parameter1 * self.parameter2
As you can see from above the Multiply class has been created with the keyword class and the method of multiplying two numbers which is called multiplying has also been created.
Now you can create an object from the above class and call its method as follows:-
mul = Multiply(10,2) print(mul.multiplying()) #20
When the object has been created for the first time, it will call the init method and put the two parameters into the init method as parameter1 and parameter2 accordingly. The self keyword inside the init or other methods will be used to refer to that object itself so you can access the elements of that object in the future, for example in the multiplying method above.
Next let us create the child class of that main class.
First of all, let us modify the above class a little bit.
class Multiply: def __init__(self, parameter1, parameter2): self.parameter1 = parameter1 self.parameter2 = parameter2 def multiplying(self): self.parameter = self.parameter1 * self.parameter2
As you can see the multiplying function no longer returns the result but instead assigns the outcome to the parameter variable which will be used later to multiply with the third parameter of the child object!
Next, let us create the child object.
class Multiply2(Multiply): def __init__(self, parameter1, parameter2, parameter3): super().__init__(parameter1, parameter2) self.parameter3 = parameter3 def result(self): self.multiplying() # multiplying the first two parameters return self.parameter * self.parameter3
Now the child class will inherit all the methods and properties of the parent class. Notice the super() method is used to call the init method of the parent class and then passed the first two parameters into that parent class.
At last, by using the self keyword under the result method you can access the parameter variable from the parent class which is actually the property of the child class itself.
Now you can create the object from the child class and get the result of three parameters that will multiply together.
mul = Multiply2(10,2, 10) print(mul.result()) # 200
That is it, and now let us all get to the last chapter of the Python tutorial.