I'm trying to understand a problem I'm having with python 2.7 right now.
Here is my code from the file test.py:
class temp:
def __init__(self):
self = dict()
self[1] = 'bla'
Then, on the terminal, I enter:
from test import temp
a=temp
if I enter a
I get this:
>>> a
<test.temp instance at 0x10e3387e8>
And if I try to read a[1]
, I get this:
>>> a[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: temp instance has no attribute '__getitem__'
Why does this happen?
First, the code you posted cannot yield the error you noted. You have not instantiated the class; a
is merely another name for temp
. So your actual error message will be:
TypeError: 'classobj' object has no attribute '__getitem__'
Even if you instantiate it (a = temp()
) it still won't do what you seem to expect. Assigning self = dict()
merely changes the value of the variable self
within your __init__()
method; it does not do anything to the instance. When the __init__()
method ends, this variable goes away, since you did not store it anywhere else.
It seems as if you might want to subclass dict
instead:
class temp(dict):
def __init__(self):
self[1] = 'bla'