Python class gotcha with scope?

Vincent phostu at gmail.com
Sun Jun 21 02:38:28 EDT 2009


On Jun 21, 2: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}
>
> thanks,
>
> billy


class Foo:
    def __init__(self):
        self.r = {}
    def setn(self,n):
        self.r['f'] = n

a = Foo()
a.setn(3)
a.r
{'f': 3}
b = Foo()
b.r
{}



More information about the Python-list mailing list