0

I am learning OOP in Python and have a query related to class and instance variables.

>>> class Something:
...     val = 10
...     def __init__(self):
...             self.instval = 100
...
>>> some = Something()
>>> some.val
10
>>> some.instval
100
>>> dir(some)
['__doc__', '__init__', '__module__', 'instval', 'val']
>>> some.val = 1000
>>> dir(some)
['__doc__', '__init__', '__module__', 'instval', 'val']
>>> some.val
1000
>>> Something.val
10
>>> del some.val
>>> some.val
10
>>> dir(some)
['__doc__', '__init__', '__module__', 'instval', 'val']

In this class i have val a class variable and instval an instance variable. I re declare the val class variable to 1000. So some.val gives me 1000 but Something.val still gives me 10. When i delete some.val it reverts back to class variable value.

I know that the interpreter first looks up a variable at instance level and then at class level. Then what is happening here ?

I have gone through some of the answers, I think this was most appropriate, but i didn't fully understand it's implications.

twitu
  • 553
  • 6
  • 12
  • See https://stackoverflow.com/a/34126204/476. `some.val = ...` creates an instance attribute, `del some.val` removes it. – deceze Nov 13 '17 at 08:37
  • @deceze Perhaps the most important part in the answer you linked is "If a class variable is set by accessing an instance, it will override the value only for that instance. This essentially overrides the class variable and turns it into an instance variable available, intuitively, only for that instance." – DeepSpace Nov 13 '17 at 08:43
  • It's really pretty straight forward: attributes are *looked up* upwards in the hierarchy, but they're not *set* upwards the hierarchy. `some.val` pretty clearly sets an attribute on `some`, not on `Something`. – deceze Nov 13 '17 at 08:58
  • Yes, the above link helped. This cleared up my misconception. – twitu Nov 13 '17 at 09:09

0 Answers0