[Tutor] class accessing another's updated property

Kent Johnson kent37 at tds.net
Wed Nov 14 14:10:07 CET 2007


ted b wrote:
> I want class One to be able to access access class
> Two's value property after its been updated. Everytime
> I try (by running, say testTwo().value) I get the
> __init__ value. The update method fro class Two is
> called elsewhere in the program, and I want class
> One's "getTwo" method to access class Two's updated
> value and give me '9' but i get '1'
> 
> Here's the code:
> 
> class One:
>    def __init__(self):
>       self.value = 3
>    def getTwo(self):
>       print "testTwo's updated value", Two().value
> 
> class Two:
>    def __init__(self):
>       self.value = 1
>    def update(self):
>       self.value = 9

value is a property of instances of Two, not of the class itself. 
getTwo() is creating a new instance of Two and reading it's value. You 
don't show the code that calls update but if it is something like
   Two().update()
then this creates an instance of Two, changes its value and throws the 
instance away.

Two options ;-) :
- Create an instance of Two which you keep in a variable and pass to 
clients.
- If you really just want Two to be a container for globally-accessible 
values, then make value a class attribute rather than an instance attribute:
class Two:
   value = 1

to update:
   Two.value = 9

class One:
   ...
   def getTwo(self):
     print Two.value

Kent


More information about the Tutor mailing list