Code Explanation:
1. Defining Class A
class A:
This line defines a new class named A.
A class is a blueprint used to create objects.
2. Defining Method in Class A
def val(self):
return 4
val() is an instance method of class A.
self refers to the current object.
This method simply returns the value 4.
3. Defining Class B (Inheritance)
class B(A):
This defines a new class B.
B(A) means B inherits from A.
So, class B has access to methods of class A.
4. Overriding Method in Class B
def val(self):
Class B overrides the val() method of class A.
This means B provides its own version of the method.
5. Calling Parent Method Using super()
return super().val() + 6
super().val() calls the parent class (A) method val().
A.val() returns 4.
Then + 6 is added:
4 + 6 = 10
So this method returns 10.
6. Creating Object and Printing Output
print(B().val())
B() creates an object of class B.
.val() calls the overridden method in class B.
The method returns 10.
print() displays:
10
Final Output
10

0 Comments:
Post a Comment