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.