[Tutor] Passing a Variable

Steven D'Aprano steve at pearwood.info
Mon Apr 4 05:44:43 CEST 2011


On Sun, Apr 03, 2011 at 08:55:25PM -0500, Ryan Strunk wrote:

> I understand that python passes variables by value and not by reference

You understand wrongly. Python is neither pass-by-value nor pass-by-reference.

I've written thousands of words on this topic before, so excuse me if I'm a 
little terse. Rather than write it all out again, I'll just point you at this 
post:

http://mail.python.org/pipermail/tutor/2010-December/080505.html

You might also like to read this:

http://effbot.org/zone/call-by-object.htm


> and
> this has not been a problem up until now. Now that I am trying to design a
> class which explicitly checks a specific variable, though, I can't fathom a
> way to do it unless I pass a direct reference, and I'm not sure that can be
> done.

One standard way to do this is to have your statistic class have a player
attribute, and then have it check the player.health attribute.


class Statistic(object):
    # Check statistics of a player.
    def __init__(self, player):
        self.player = player
    def check_health(self):
        if self.player.health < 0:
             print "Bam, you're dead!"


An alternative is to have the player object check its own health, calling 
some appropriate notification object. This could be a global variable, or
an attribute of the player (that way each player could have their own 
notification user-interface).

notifier = Notify(sound='on', health_bar='off')  # whatever...

class Player(object):
    def __init__(self):
        self.health = 100
    def check_health(self):
        if self.health < 0:
            notifier.announce_dead(self)
        elif self.health < 10:
            notifer.announce_critical(self)
        else:
            notifier.announce_normal(self)


Or any of many variations on these.

              

-- 
Steven



More information about the Tutor mailing list