class scope questions

Steve Holden sholden at holdenweb.com
Fri Feb 9 17:41:49 CET 2001


"Duncan Booth" <duncan at rcp.co.uk> wrote in message
news:Xns90436DAD61713duncanrcpcouk at 127.0.0.1...
> "Ben de Luca" <c941520 at alinga.newcastle.edu.au> wrote in
> <3a83bea8$0$16388$7f31c96c at news01.syd.optusnet.com.au>:
>
> >if i do this
> >
> >class a:
> >         dog='woof'
> >
> >          def blah():
> >                    something
> >
> >
> >
> >how do i call a
> >how do i get soemthing in blah to refernce dog? either to read it or
> >write to it
> >
> class a:
>     dog='woof'
>     def blah(self):
>         print self.dog
>     def update(self, value):
>         self.dog = value
> >>> a1 = a()
> >>> a1.blah()
> woof
> >>> a1.update('bow wow')
> >>> a2 = a()
> >>> a2.blah()
> woof
> >>> a1.blah()
> bow wow
> >>>
>
> But, although this works fine, there is a problem with it. dog is
> actually a variable in the class a until it is set by the update method
> when it becomes  a variable in the instance a1. This works fine for
> strings, but if you used a mutable object such as a list or dictionary
> you would see that dog was shared between all instances of the class:
> class B: list = []
> def show(self):
> print self.list
> def append(self, value):
> self.list.append(value)
>
>
> >>> b1 = B()
> >>> b1.append('hello')
> >>> b1.show()
> ['hello']
> >>> b2 = B()
> >>> b2.show()
> ['hello']
> >>> b2.append('world')
> >>> b1.show()
> ['hello', 'world']
>
> To avoid this you should generally define an __init__ method in your
> class and use that to initialise any instance variables.
>
Note, however:

>>> a.dog
'woof'
>>>

If dog is really intended to be a class variable, shared among all
instances, then you are much safer treating it as an attribute of the class.

regards
 Steve





More information about the Python-list mailing list