Python class gotcha with scope?

Vincent phostu at gmail.com
Sun Jun 21 02:40:04 EDT 2009


On Jun 21, 2:38 pm, Vincent <pho... at gmail.com> wrote:
> 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
> {}

you defined r as class-level variable.
and i defined r as instance-level variable.



More information about the Python-list mailing list