Code Explanation:
Line 1 — Create Class A
class A:
class keyword is used to create a class.
A is the name of the parent class.
This class contains a method called show().
Line 2 — Define show() Method
def show(self):
def is used to define a function or method.
show() is a method of class A.
self refers to the current object.
Line 3 — Return "A"
return "A"
Whenever show() from class A is called, it returns the string "A".
For example:
obj = A()
print(obj.show())
Output:
A
Line 4 — Create Class B from A
class B(A):
Class B inherits from class A.
A is the parent class.
B is the child class.
Because of inheritance, B can access methods from A.
Line 5 — Define show() Again
def show(self):
Class B defines its own show() method.
This method has the same name as the method in class A.
This is called method overriding.
Line 6 — Return "B"
return "B"
When show() is called through a B object, Python uses the show() method defined inside B.
Therefore, it returns "B" instead of "A".
Line 7 — Create Object of B
x = B()
An object named x is created from class B.
Since B inherits from A, the object can also access inherited features.
However, B has its own version of show().
Line 8 — Call show() and Print Result
print(x.show())
x.show() calls the show() method.
Since x is an object of class B, Python finds the overridden show() method in B.
That method returns "B".
print() displays the returned value.
Output
B

0 Comments:
Post a Comment