Python class gotcha with scope?

billy billy.chasen at gmail.com
Sun Jun 21 02:53:05 EDT 2009


great, thanks for the quick responses :)


On Jun 21, 2:41 am, Carl Banks <pavlovevide... at gmail.com> wrote:
> 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