简体   繁体   中英

Delegates in python

I've implemented this short example to try to demonstrate a simple delegation pattern. My question is. Does this look like I've understood delegation right?

class Handler:
    def __init__(self, parent = None):
        self.parent = parent
    def Handle(self, event):
        handler = 'Handle_' +event
        if hasattr(self, handler):
            func = getattr(self, handler)
            func()
        elif self.parent:
            self.parent.Handle(event)

class Geo():
    def __init__(self, h):
        self.handler = h

    def Handle(self, event):
        func = getattr(self.handler, 'Handle')
        func(event)

class Steve():
    def __init__(self, h):
        self.handler = h

    def Handle(self, event):
        func = getattr(self.handler, 'Handle')
        func(event)

class Andy():
    def Handle(self, event):
        print 'Andy is handling %s' %(event)

if __name__ == '__main__':        
    a = Andy()
    s = Steve(a)
    g = Geo(s)
    g.Handle('lab on fire')

One Python tip: you don't need to say:

func = getattr(self.handler, 'Handle')
func(event)

just say:

self.handler.Handle(event)

I'm not sure what you are doing with your Handler class, it isn't used in your example.

And in Python, methods with upper-case names are very very unusual, usually a result of porting some existing API with names like that.

这是基本概念,是的 - 将一些传入请求传递给另一个对象来处理。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM