python中的委托
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3643538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delegates in python
提问by MattyW
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')
采纳答案by Amber
That's the basic concept, yes - passing on some incoming request to another object to take care of.
这是基本概念,是的 - 将一些传入请求传递给另一个对象来处理。
回答by Ned Batchelder
One Python tip: you don't need to say:
一个 Python 提示:您无需说:
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.
我不确定你在用你的 Handler 类做什么,它没有在你的例子中使用。
And in Python, methods with upper-case names are very very unusual, usually a result of porting some existing API with names like that.
在 Python 中,具有大写名称的方法非常不寻常,通常是移植一些具有类似名称的现有 API 的结果。

