Python class gotcha with scope?

billy billy.chasen at gmail.com
Sun Jun 21 02:32:04 EDT 2009


I don't quite understand why this happens. Why doesn't b have its own
version of r? If r was just an int instead of a dict, then it would.

>>> class foo:
...     r = {}
...     def setn(self, n):
...             self.r["f"] = n
...
>>> a = foo()
>>> a.setn(4)
>>>
>>> b = foo()
>>> b.r
{'f': 4}

thanks,

billy



More information about the Python-list mailing list