Search code examples
pythoninstance-variablesclass-variables

Python : Behavior of class and instance variables


I have following two code samples

Example 1:

class MyClass(object):

    def __init__(self, key, value):
         self._dict = self._dict.update({key:value})

m = MyClass('ten',10)
print m._dict

Output:

AttributeError: 'MyClass' object has no attribute '_dict'

Example2:

class MyClass(object):
    _dict = {}
    def __init__(self, key, value):
        self._dict = self._dict.update({key:value})

m = MyClass('ten',10)
print m._dict

Output: None

I am quite surprised with above behavior

Why the example2 compiled successfully by just addition of _dict = {} line, and line present at class scope. also why None output? I believed class scope variables has no relation with instance variable (special with self)

Any Explaination?


Solution

  • The None output is because dict.update returns None. It modifies the dictionary itself, but does not return anything. So you probably wanted self._dict.update({key:value}). However, self._dict doesn't exist at initialization. So it would make more sense to do self._dict = {key: value}. If you're trying to modify the object's internal dictionary, then you should do self.__dict__.update({key:value}). However, this is bad practice. A better idea would be to write setattr(self, key, value). The reason Example2 is working successfully is because if you try to do getattr(instance, thing) (which is what instance.thing does), and thing is not in instance.__dict__, then instance.__class__.__dict__ will be checked instead.