我有下面的代码片断:动态添加类方法对类
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)对于每个进料的类型。它的工作原理差不多大,唯一的问题是,打印语句总是打印“通知new_event”,不论何种方法我称之为(同为notify_new_mail,notify_review等)。
我意识到这是因为它使用了分配给类型的最后一个值。我的问题是:我如何动态创建方法使用类型的正确值?
另外,如果我在Python文件中有这个确切的代码,那是将方法添加到Feed类的正确方法,还是有更优雅的方法?
谢谢! 'notify = make_notify(typ)'和'notify .__ name__ ='notify_%s'%typ'行应该使用'type'(而不是'typ'),对吗? – kolrie 2013-03-14 22:17:58
糟糕,'self.create(type,...)'应该是'self.create(typ,...)'。在你写'type'的地方,我建议使用不同的东西,也许'kind',以便将它与Python内建完全区分开来。 – unutbu 2013-03-14 22:22:42
喜欢类装饰者的概念! – kolrie 2013-03-14 23:01:24