跳到主要內容

發表文章

目前顯示的是 10月, 2012的文章

Using descriptor as explicit delegation in Python

Descriptors in Python is an interesting approach to simplifying many difficult design problems. I would like to share one of my application of this useful feature. Consider the following code snippet: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class MailEvent ( object ): def fire ( self , instance , cls ): print "handling mail event from " + str ( cls . __name__ ) + " " + str ( instance . name ) class LogEvent ( object ): def fire ( self , instance , cls ): print "handling log event from " + str ( cls . __name__ ) + " " + str ( instance . name ) # using inheritance class BaseWorker ( object ): def __init__ ( self , name ): self . name = name self . event_factory = { "mail" : MailEvent (), "log" : LogEvent ()} def event ( self , evt ): if evt in self . event_factory : self .