1
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?

Searene
  • 25,920
  • 39
  • 129
  • 186
  • 2
    You will be glad in the long run if you acquire good naming habits, such as those described in PEP8. Classname 'test' is indistinguishable from a function in the statement `t = test()`, but if you capitalize your classnames, then `t = Test()` is very clearly constructing a new instance of the class Test. – PaulMcG Feb 24 '12 at 12:53

3 Answers3

6

You forgot self.

Change this:

def __init__(self):
    test_dict = {'1': 'one', '2': 'two'}

with:

def __init__(self):
    self.test_dict = {'1': 'one', '2': 'two'}

self is your instance inside the methods in your class. That is not because self is a special keyword but because self is usually the word choosen to be a method first argument.

If you want to know more about self, there's a good answer here.

At the end notice that you got an AttributeError when you tried to call

t.test_dict

beacuse the test_dict attribute was not defined.

Community
  • 1
  • 1
Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
1

You made an error in your __init__. This:

    def __init__(self):
        test_dict = {'1': 'one', '2': 'two'}

Should be:

    def __init__(self):
        self.test_dict = {'1': 'one', '2': 'two'}
orlp
  • 112,504
  • 36
  • 218
  • 315
0

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:

self.test_dict = ...

like

self.__dict__["test_dict"] = ...

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.

Samvel
  • 182
  • 2
  • 6