class test:
def __init__(self):
test_dict = {'1': 'one', '2': 'two'}
def test_function(self):
print self.test_dict
if __name__ == '__main__':
t = test()
print t.test_dict
Error:
AttributeError: test instance has no attribute 'test_dict'
Also, if i execute code: t.test_function() instead of print t.test_dict, error occurred too:
AttributeError: test instance has no attribute 'test_dict'
Why? i have defined test_dict in function __init__, so it should be initialized to each instance, but why does python tell me it cannot find the dict?
Think of classes/instances as dictionaries. Whenever you create instance and call any of its methods, these functions automatically receive instance as first argument (unless function is static or class method).
So, if you want some variable to be stored in instance and later be accessed, put all variables into that first argument (by convention, it is called self).
Class constructor is not an exception of the above rule. That’s why all answers point out a change in the constructor in test_dict assignment.
Think of:
like
Like will all variables in Python, you can not access it if variable was not assigned first. This is the case in your original class:
_init_ has created a local (to method) variable, while test_function is trying to access instance variable in dictionary, which does not exist.