【发布时间】:2013-03-14 21:58:13
【问题描述】:
我有以下sn-p:
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'),
]
class Feed:
@classmethod
def do_create(cls, **kwargs):
print kwargs
@classmethod
def create(cls, type, **kwargs):
kwargs['feed_type'] = type
cls.do_create(**kwargs)
for type_tuple in FEED_TYPES:
type, name = type_tuple
def notify(self, **kwargs):
print "notifying %s" % type
self.create(type, **kwargs)
notify.__name__ = "notify_%s" % type
setattr(Feed, notify.__name__, classmethod(notify))
Feed.create("FanMail", to_profile="Gerson", from_profile="Felipe")
Feed.notify_fan_mail(to_profile="Gerson2", from_profile="Felipe2")
我们的想法是为每种提要类型动态创建一个类方法(如 notify_fan_mail)。它几乎工作得很好,唯一的问题是 print 语句总是打印“通知 new_event”,无论我调用什么方法(对于 notify_new_mail、notify_review 等)。
我意识到这是因为它使用了分配给类型的最后一个值。我的问题是:如何动态创建可以为 type 使用正确值的方法?
另外,如果我在 Python 文件中有这个确切的代码,那是向 Feed 类添加方法的正确方法,还是有更优雅的方法?
【问题讨论】:
标签: python metaprogramming class-method