Python 使用decorator收集实例方法?
我有这门课:Python 使用decorator收集实例方法?,python,Python,我有这门课: class Foo(object): handlers = [] def __init__(self): pass def run(self): pass def foo(self): pass def bar(self): pass 如何实现decorator@collect\u处理程序 class Foo(object): handlers = []
class Foo(object):
handlers = []
def __init__(self):
pass
def run(self):
pass
def foo(self):
pass
def bar(self):
pass
如何实现decorator@collect\u处理程序
class Foo(object):
handlers = []
def __init__(self):
pass
def run(self):
pass
@collect_handler
def foo(self):
pass
@collect_handler
def bar(self):
pass
以便:
foo = Foo()
foo.handlers # [foo, bar]
?
这可能吗
class Foo(object):
handlers = []
def collect_handler(handlers):
def wrapper(func):
handlers.append(func)
return func
return wrapper
collect_handler = collect_handler(handlers)
def __init__(self):
pass
def run(self):
pass
@collect_handler
def foo(self):
pass
@collect_handler
def bar(self):
pass
foo = Foo()
print(foo.handlers)
屈服
[<function foo at 0xb770d994>, <function bar at 0xb770d9cc>]
[,]
这些不是未绑定的方法;它们只是简单的函数。(没有检查第一个参数是否是
Foo
的实例)但是,它们应该足够了。(注意在Python3中没有更多的未绑定方法;取消了未绑定方法和普通函数之间的区别。)只是一种不使用装饰器的替代方法
f = Foo()
[m for m in dir(f) if getattr(f,m).__doc__ == "COLLECT"]
上述语句使用Python中的列表理解。dir
是一个内置函数,它将返回对象的所有属性。getattr
是一个内置函数,用于检索对象的属性。\uuuu doc\uuuu
是一个python变量,它保存任何python工件的docstring
这应该是您的类定义:
class Foo(object):
def __init__(self):
pass
def run(self):
pass
def foo(self):
"COLLECT"
pass
def bar(self):
"COLLECT"
pass
您希望
处理程序返回绑定实例方法还是未绑定实例方法?