Bug or Feature with (overriding) Class Variables?

Peter Otten __peter__ at web.de
Sun Nov 16 10:24:20 CET 2003


Eric Baker wrote:

> With this little snippet, i get an inconsistency between the behavior
> of string and dictionary class variables:
> 
> Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> IDLE 0.8 -- press F1 for help
>>>> class foo:
>         dict = {}
>         string = "foostring"
>         def bar(self):

Here you are changing the value of foo.dict. The equivalent to the following
line where you are rebinding the value of self.string would be:

self.dict = {"bar-key": "bar-value}

>                 self.dict["bar-key"] = "bar-value"
>                 self.string = "bar-string"

But there's a twist: when you say fooinstance.attribute, attribute ist first
looked up in the instance, and then if not found, in the class. So
depending on the context, fooinstance.attribute may refer to a class or an
instance attribute. On the other hand, fooinstance.attribute = somevalue
will always rebind the instance attribute, to rebind the class attribute
you can do

foo.attribute = somevalue

or

fooinstance.__class__.attribute = somevalue

> Question: Which behavior is the correct one?

Both.

> Question: Is this a bug or a feature?

Feature that bugs you?


Peter




More information about the Python-list mailing list