[Edu-sig] Python Pedagogy

Dan Crosta dcrosta at sccs.swarthmore.edu
Fri Jul 21 19:04:16 CEST 2006


Andre Roberge wrote:
> Well, while we're at it:
> class Human:
>    def __init__(my, name):
>        my.name = name
>        I = my
> 
>    def __repr__(my):
>        return 'My name is %s' % my.name
> 
>    def is_hungry(I):
>        print "I am hungry."
>        I.eat()
> 
>    def eat(I):
>        print "I eat!"
> 
> Kirby = Human("Kirby")
> print Kirby
> Kirby.is_hungry()

I don't really know how decorators work, but wouldn't it be possible to 
write a decorator that would let you define functions like this:


class Human:
	def __init__(my, name):
		my.stomach_state = 'empty'
		my.name = name

	@wackydecorator
	def is_hungry(I, my):
		print "%s stomach is %s" % (my.name, my.stomach_state)
		
		if my.stomach_state != 'full':
			I.eat()

	def eat(my):
		my.stomach_state = 'full'

kirby = Human("Kirby")
kirby.is_hungry()
kirby.is_hungry()

====

so basically the decorator would duplicate the first argument twice so 
that you could transparently get two (or more) names for it... I don't 
know how to write decorators (and can't really spend time learning here 
at work), but something like this:

def wackydecorator(func, *args):
	return func(args[0], *args)

I think that would do the trick.

- d


More information about the Edu-sig mailing list