[Tutor] Passing a Variable

Andre Engels andreengels at gmail.com
Mon Apr 4 12:09:29 CEST 2011


On Mon, Apr 4, 2011 at 7:27 AM, Ryan Strunk <ryan.strunk at gmail.com> wrote:
>> I've read your code. Frankly I don't understand your problem. I also don't
> see any occurrence of "health".
> There isn't a reference to health here. My goal is to have this code act as
> a checker for health, fatigue, time_remaining, or any other sort of
> statistic you'd like to throw into it. My problem is that when I try:
> instance = Statistic(stat=health, sound=spam, low=1, mid=15, high=30)
> health can change elsewhere in the program, but the instance of statistic
> class won't automatically see it.

My proposal would be to wrap the stats in an object:

Class stat:
     __init__(self, name, value)
     self.type = name
     self.value = value

Then in the player object change the initialisation

health = startvalue

to

health = stat("health", startvalue)

and change every other reference to health to a reference to health.value.

Then you can use the current code if you replace self.stat outside the
__init__ by self.stat.value

You could even consider merging the stats and Statistics classes.

======

Another possibility would be to use a getter method and the fact that
methods are objects:

In the player object add:

def get_health(self):
    return self.health

change the call to:

instance = Statistic(stat=get_health, sound=spam, low=1, mid=15, high=30)

and replace self.stat by self.stat() everywhere in the Statistics code

-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list