I'd like to mark some methods (class methods in this case, but not necessarily) as related so I can use them together. I don't want to create a hardcoded list of the methods inside all_fruit
because I don't want it to be missed when adding a new type of fruit. Ideally, I'd be able to do something like this:
class Food:
@classmethod
@fruitdecorator
def apples(clss, amount):
return '%d apple(s)' % amount
@classmethod
@fruitdecorator
def oranges(clss, amount):
return '%d orange(s)' % amount
@classmethod
def carrots(clss, amount):
return '%d carrot(s)' % amount
@classmethod
def all_fruit(clss, amount):
pass # somehow return all methods decorated by @fruitdecorator
for method in Food.all_fruit():
print method(Food, 2)
# '2 apples'
# '2 oranges'
I found these decorator answers which let me do the following, which is OK, but I was wondering if it could be simplified at all. In this case I have to define this stuff and call it before, after, and use it in the fruit_baseket class method, which seems a little tedious. (I'm open to non-decorator solutions but they seem like the best way to keep the "mark" and the function definition close together.)
def MakeDecorator():
registry = []
def decorator(fn):
# print dir(fn)
registry.append(fn)
return fn
decorator.all = registry
return decorator
fruitdecorator = MakeDecorator()
class Food:
@classmethod
@fruitdecorator
def apples(clss, amount):
return '%d apple(s)' % amount
@classmethod
@fruitdecorator
def oranges(clss, amount):
return '%d orange(s)' % amount
@classmethod
def carrots(clss, amount):
return '%d carrot(s)' % amount
@classmethod
def fruit_basket(clss, amount):
basket = [xx(clss, amount) for xx in clss.fruit_methods]
return basket
Food.fruit_methods = fruitdecorator.all
print Food.fruit_basket(2)