What happens when accessing an attribute from a Class vs an instance in python? -
i trying understand access of attributes class vs object. experiment this:
>>> class test(): x = 1 y = 2 def __init__(self, a, b): self.x = self.y = b >>> test.x, test.y (1, 2) >>> t = test(3, 4) >>> (t.x, t.y) (3, 4) # looks class attributes , instance attributes completed unrelated, ... >>> del t.x >>> del t.y >>> t.x, t.y (1, 2) # looks instance attributes shadows class attributes, # accessed when instance attrs not present, ... >>> t.x = 5 # expected class attributes changed, ... >>> test.x 1 # class attribute not changed >>> t.x 5
what happens when try access attribute (read/write/delete)?
and why python designed way?
you're correct instance attributes shadow class attributes. in __init__
method , in t.x = 5
, you're adding attributes instance. way create instance attributes.
Comments
Post a Comment