Python class gotcha with scope?

Carl Banks pavlovevidence at gmail.com
Sun Jun 21 02:41:03 EDT 2009


On Jun 20, 11:32 pm, billy <billy.cha... at gmail.com> wrote:
> 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}

r is a class attribute, that is, it is attacted to the class itself.
Look at what happens when you enter foo.r at the interactive prompt:

>>> foo.r
{'f': 4}


You want an instance attribute, a value attached to the instance of
the class.  You create those in the __init__ method:


class foo:
    def __init__(self):
        self.r = {}
    def setn(self,n):
        self.r["n"] = n



Carl Banks



More information about the Python-list mailing list