Code Explanation:
class A:
This defines a class named A. In Python, classes are blueprints for creating objects.
def __init__(self): self.x = 1
This defines the constructor method for class A. It is automatically called when an object of class A is created.
self.x = 1 sets an instance variable x to 1 for any object of class A.
So, when you do A(), it creates an object with x = 1.
class B(A):
This defines another class B, which inherits from class A. That means B gets all the methods and properties of A unless they are overridden.
def __init__(self): super().__init__(); self.x = 2
This is the constructor for class B.
super().__init__() calls the constructor of the parent class (A) — so it sets self.x = 1.
Immediately after that, self.x = 2 overrides the earlier value.
So, any object of class B will have x = 2, because self.x = 2 comes after the parent’s initialization.
print(A().x, B().x)
Now this prints the value of x for instances of both classes:
A().x creates an object of class A, which sets x = 1, and then prints that value.
B().x creates an object of class B, which first sets x = 1 (via super().__init__()), then changes it to 2, and prints that.
Final Output:
1 2
0 Comments:
Post a Comment