setting an attribute

half.italian at gmail.com half.italian at gmail.com
Wed May 16 04:40:56 EDT 2007


On May 16, 12:34 am, 7stud <bbxx789_0... at yahoo.com> wrote:
> "When you bind (on either a class or an instance) an attribute whose
> name is not special...you affect only the __dict__ entry for the
> attribute(in the class or instance, respectively)."
>
> In light of that statement, how would one explain the output of this
> code:
>
> class Test(object):
>     x = [1, 2]
>
>     def __init__(self):
>         self.x[0] = 10
>
> print Test.__dict__    #{.....'x':[1,2]....}
> t = Test()
> print t.x              #[10, 2]
> print t.__dict__       #{}
> print Test.__dict__    #{.....'x':[10,2]...}
>
> It looks to me like self.x[0] is binding on an instance whose
> attribute name is not special, yet it doesn't affect any __dict__
> entry for the attribute in the instance--instead it is affecting a
> __dict__ entry for the attribute in the class.

I think it's following scope rules.  It can't find an attribute for
self.x in the instance.  It then checks the class for the var and
finds it and sets it there.  It would error otherwise...

>>> class Test(object):
...     def __init__(self):
...             self.x[0] =7
...
>>> t = Test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
AttributeError: 'Test' object has no attribute 'x'

~Sean




More information about the Python-list mailing list