Python pass class instance to its method (function) decorators
我要执行以下操作:我有一个班,那个班有一个名为"命令"的口述。我想通过装饰器动态地向它添加元素。decorator应该是一个函数,一个此类的方法。我想要的示例代码:
1 2 3 4 5 6 7 8 9 | class Foo(object): #In a class: @cmd("exit") def cmd_exit(self, *args): self.run=0 print("Exiting mainloop...") @cmd('reconnect') def cmd_reconnect(self): self.connect(self._host) |
为了实现这一点,我需要将self传递给方法
1 2 3 4 5 6 7 | def cmd(self, name): def decorator(funcs): fname=name if name else funcs.__name__ self.cmds[fname]=funcs self.cmdLogger.info("Registrated function %s", name) return return decorator |
号
它只接收我传递给装饰器的字符串(例如"exit"和"reconnect")。请注意,内部装饰器(称为decorator)返回
您可以从另一个类继承"cmds",以跟踪"中心位置"中的日志:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | from functools import wraps def cmd(*name): def wrapper(fn): @wraps(fn) def real_decorator(*args, **kw): fname = name[0] if name else fn.__name__ cls = args[0] cls.cmds[fname]=fn #self.cmdLogger.info("Registrated function %s", name) return fn(*args,**kw) return real_decorator return wrapper class Logger(object): def __init__(self): self.cmds = {} #self.cmdLogger = ... class Foo(Logger): @cmd("exit") def cmd_exit(self, *args): self.run=0 print("Exiting mainloop...") @cmd('reconnect') def cmd_reconnect(self): self.connect(self._host) f = Foo() f.cmd_exit() print(f.cmds) |
返回:
1 2 | Exiting mainloop... {'exit': <function Foo.cmd_exit at 0x7fb11cfee048>} |
号