Why won't this decorator work?

OKB (not okblacke) brenNOSPAMbarn at NObrenSPAMbarn.net
Sun Jul 3 20:01:51 CEST 2011

John Salerno wrote:

> Basically what I want to do is this: I first to need to roll a die to
> get a random number, then pass that number to the move method of a
> Player class. Can this be done with a decorator, or is it better just
> to do it like move(roll_die()) and be done with it?

    	A decorator basically modifies a function/method, so that ALL 
subsequent calls to it will behave differently.  If you want ALL calls 
to your method to roll a die to get a random number, and then use that 
random number, why not just roll the die inside the method itself:

def move(dist=None):
    	if dist=None:
    	    	dist = random.randint(1, 7)
    	# etc

    	If you don't want all calls to your method to roll the die, but 
only some, and if the choice of whether to roll or not depends on 
information outside the method, then you need to do the rolling outside 
the method and pass the result in.  This is more or less what other 
people have mentioned (and what you seem to have also been considering):

# In code that wants to move the player. . .
if doIWantToMoveRandomly():
    	player.move(2) # or whatever non-random expression you want

--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
	--author unknown

More information about the Python-list mailing list