class scope questions
Duncan Booth
duncan at rcp.co.uk
Fri Feb 9 05:48:31 EST 2001
"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.
More information about the Python-list
mailing list