我有下面的代碼片斷:動態添加類方法對類
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