Code Explanation:
1. Defining the Base Class
class Base:
value = 5
A class named Base is created.
It contains a class variable value set to 5.
Class variables are shared by all objects unless overridden in a child class.
2. Defining the Child Class
class Child(Base):
A new class Child is defined.
It inherits from Base, so it automatically gets anything inside Base unless redefined.
3. Overriding the Class Variable
value = 9
Child defines its own class variable named value, set to 9.
This overrides the value inherited from Base.
Now, for objects of Child, value = 9 is used instead of 5.
4. Method Definition inside Child
def show(self):
return self.value
A method named show() is created.
It returns self.value, meaning it looks for the attribute named value in the object/class.
Since Child has overridden value, it will return 9.
5. Creating an Object of Child
c = Child()
An instance c of class Child is created.
It automatically has access to everything defined in Child and anything inherited from Base.
6. Calling the Method
print(c.show())
Calls the method show() on the object c.
This returns the overridden value (9) from the Child class.
Python prints:
9
Final Output: 9


0 Comments:
Post a Comment