Code Explanation:
๐น 1. Defining Class A
class A:
Creates a base class named A
Inherits from object by default
๐น 2. Defining a Method in Class A
def x(self):
return "method"
x is an instance method
Stored in the class namespace of A
Normally accessed as A().x() and returns "method"
๐ Important concept:
Methods are just attributes that happen to be callable.
๐น 3. Defining Class B (Inheritance)
class B(A):
B inherits from A
So B inherits method x from A initially
๐น 4. Defining a Class Attribute with the Same Name
x = "attribute"
This creates a class attribute named x in B
This overrides (shadows) A.x
B.x is now a string, not a method
๐ Even though A.x is a method, Python does not treat it specially —
it’s just another attribute name.
๐น 5. Creating an Object of Class B
B()
Creates an instance of class B
No instance attribute named x exists yet
๐น 6. Accessing B().x
print(B().x)
Attribute lookup order:
Instance dictionary (obj.__dict__) → ❌ no x
Class B → ✅ finds x = "attribute"
Stops lookup (parent A is never checked)
๐ Because B.x exists, A.x is ignored.
✅ Final Output
attribute

0 Comments:
Post a Comment