使用闭包来保存值kind
:
for type_tuple in FEED_TYPES:
kind, name = type_tuple
def make_notify(kind):
def notify(self, **kwargs):
print "notifying %s" % kind
self.create(kind, **kwargs)
return notify
notify = make_notify(kind)
notify.__name__ = "notify_%s" % kind
setattr(cls, notify.__name__, classmethod(notify))
顺便说一句,不要使用type
作为变量名,因为它隐藏了同名的内置函数。
更优雅的修改方式Feed
就是创建一个类装饰器。这使得您可以更清楚地看出您的代码修改了原始定义Feed
.
FEED_TYPES = [
('fan_mail', 'Fan Mail'),
('review', 'Review'),
('tip', 'Tip'),
('fan_user', 'Fan User'),
('fan_song', 'Fan Song'),
('fan_album', 'Fan Album'),
('played_song', 'Played Song'),
('played_album', 'Played Album'),
('played_radio', 'Played Radio'),
('new_event', 'New Event'),
]
def add_feed_types(cls):
for type_tuple in FEED_TYPES:
kind, name = type_tuple
def make_notify(kind):
def notify(self, **kwargs):
print "notifying %s" % kind
self.create(kind, **kwargs)
return notify
notify = make_notify(kind)
notify.__name__ = "notify_%s" % kind
setattr(cls, notify.__name__, classmethod(notify))
return cls
@add_feed_types
class Feed:
@classmethod
def do_create(cls, **kwargs):
print kwargs
@classmethod
def create(cls, kind, **kwargs):
kwargs['feed_type'] = kind
cls.do_create(**kwargs)
Feed.create("FanMail", to_profile="Gerson", from_profile="Felipe")
Feed.notify_fan_mail(to_profile="Gerson2", from_profile="Felipe2")