Bug or Feature with (overriding) Class Variables?

Eric Baker google.com.112139 at satilla.com
Sun Nov 16 10:01:17 CET 2003


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):
                self.dict["bar-key"] = "bar-value"
                self.string = "bar-string"



>>> # Lets create an instance of Foo
>>> baz = foo()
>>> baz.dict
{}
>>> baz.string
'foostring'
>>> # No suprises yet, the class variables are shown
>>>
>>> # Now lets call bar() and change some vars
>>> baz.bar()
>>> baz.dict
{'bar-key': 'bar-value'}
>>> # Did it return a class variable or an instance variable?
>>> baz.__class__.dict
{'bar-key': 'bar-value'}
>>> # As you can see, both show the same values
>>>
>>> baz.dict is baz.__class__.dict
1
>>> # So we see that both are actually the same instance
>>> # of the dictionary class
>>>
>>> # Now we look at the string
>>> baz.string
'bar-string'
>>> # Obviously this was the instance variable
>>> baz.__class__.string
'foostring'
>>> # And this was the class variable
>>> baz.string is baz.__class__.string
0
>>> # And we actually can see, that they are different
>>> # instances of the string class

Question: Which behavior is the correct one?
Question: Is this a bug or a feature?




More information about the Python-list mailing list