Code Explanation:
1. Class Definition
class Device:
mode = "auto"
Explanation:
class Device:
→ This defines a class named Device.
mode = "auto"
→ This is a class variable.
It belongs to the class itself, not to any specific object.
All objects of Device can access this variable unless overridden.
2. Creating an Object
d = Device()
Explanation:
Device()
→ Creates a new object (instance) of the Device class.
d =
→ Stores that object in the variable d.
At this point:
d does not have its own mode
It uses Device.mode → "auto"
3. Accessing the Variable
print(d.mode)
Explanation:
Python looks for mode inside object d.
Since d has no instance variable called mode,
Python checks the class variable Device.mode.
Output:
auto
4. Modifying the Variable
d.mode = "manual"
Explanation:
This creates a new instance variable mode inside d only.
It does NOT change the class variable.
Now:
d.mode → "manual"
Device.mode → "auto"
5. Printing Class vs Object Variable
print(Device.mode, d.mode)
Explanation:
Device.mode
→ Refers to the class variable → "auto"
d.mode
→ Refers to the instance variable → "manual"
Output:
auto auto manual

0 Comments:
Post a Comment