这是Python 2.5,它也是GAE,并不重要.
我有以下代码.我正在使用dec_check类作为装饰器在bar中装饰foo()方法.
class dec_check(object):
def __init__(self, f):
self.func = f
def __call__(self):
print 'In dec_check.__init__()'
self.func()
class bar(object):
@dec_check
def foo(self):
print 'In bar.foo()'
b = bar()
b.foo()
Run Code Online (Sandbox Code Playgroud)
执行此操作时,我希望看到:
In dec_check.__init__()
In bar.foo()
Run Code Online (Sandbox Code Playgroud)
但我得到" TypeError: foo() takes exactly 1 argument (0 given)"作为.foo()一种对象方法,以自我为参数.我猜测问题是bar当我执行装饰器代码时,实例并不存在.
那么如何将一个实例传递bar给装饰器类呢?
我见过很多Python装饰器的例子:
__init__,__get__和__call__)但我从来没有见过一个可以完成上述所有工作的例子,而且我很难从特定问题的各种答案中综合出来(比如这一个,这一个,或者这一个(它有一个最好的答案)我曾见过SO)),如何结合以上所有内容.
我想要的是一个基于类的装饰器,它可以装饰方法或函数,并且至少需要一个额外的参数.即以下内容可行:
class MyDecorator(object):
def __init__(self, fn, argument):
self.fn = fn
self.arg = argument
def __get__(self, ....):
# voodoo magic for handling distinction between method and function here
def __call__(self, *args, *kwargs):
print "In my decorator before call, with arg %s" % self.arg
self.fn(*args, **kwargs)
print "In my decorator after call, with arg %s" …Run Code Online (Sandbox Code Playgroud) 当我向Telegram Bot发送消息时,它没有任何问题.
我想限制访问,以便我和只有我可以向它发送消息.
我怎样才能做到这一点?
我的目标是我不会有一个可以同时使用函数和实例方法的装饰器,并且self当装饰器应用于方法时,我想在包装函数中检索对象;当应用于函数时,我想检索函数对象本身。 。
这是我发现几乎可以正常使用的功能,这只是我用来检测已应用哪种装饰器的功能:
def _is_method(func):
for stack_frame in inspect.stack():
# if the code_context of the stack frame starts with 'class' this
# function is defined within a class and so a method.
if inspect.getframeinfo(stack_frame[0]).code_context[0].strip().startswith('class'):
return True
return False
Run Code Online (Sandbox Code Playgroud)
这确实对我有用,只有一个小例外,当我在多个进程中并行运行测试时,它将引发例外。
我有一个装饰师
def deco(func):
def inner(params):
#< DO STUFF WITH func >
return inner
Run Code Online (Sandbox Code Playgroud)
和一个基类
class GenericClass:
def __init__(self,value):
self.value = value
def method(self,params):
print 'NOT IMPLEMENTED YET'
def other_method(self):
print 'GOOD TO GO'
Run Code Online (Sandbox Code Playgroud)
我希望能够在 GenericClass 的子类上装饰“method”方法,例如检查输入/输出或处理异常(方法“method”将被覆盖)
我想做的是...
class ChildClass(GenericClass):
@deco
def method(self,params):
#< NEW METHOD >
Run Code Online (Sandbox Code Playgroud)
我不是专家Python开发人员,该级别的所有文档都非常混乱(即元类、装饰器的微妙之处、__call__方法等),而且我没有找到解决方案。