I mają następujące fragmentu:klasy dynamicznej metody dodawania do klasy
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")
Idea jest do dynamicznego tworzenia jednej metody klasy (np notify_fan_mail) dla każdego rodzaju posuwu. Działa prawie świetnie, jedynym problemem jest to, że instrukcja drukuje zawsze drukuje "powiadamiając new_event", niezależnie od metody, którą wywołuję (to samo dla notify_new_mail, notify_review, itp.).
Rozumiem, że to dlatego, że używa ostatniej wartości przypisanej do typu. Moje pytanie brzmi: jak mogę dynamicznie tworzyć metody, które używają poprawnej wartości dla typu?
Ponadto, jeśli mam ten dokładny kod w pliku Python, czy jest to właściwy sposób dodawania metod do klasy Feed lub czy istnieje bardziej elegancki sposób?
Dziękujemy! Wiersze 'notify = make_notify (typ)' oraz 'notify .__ name__ =" notify_% s "% typ' powinny używać' type' (zamiast 'typ'), poprawne? – kolrie
Ups, 'self.create (type, ...)' powinno być 'self.create (typ, ...)'.Wszędzie, gdzie napisałeś 'type', sugeruję użycie czegoś innego, może" rodzaju "zamiast - całkowicie odróżnić go od wbudowanego w Python. – unutbu
Uwielbiam koncepcję dekoratora klasy! – kolrie