无法使用python中其他文件中定义的装饰器
我正在尝试使用decorator打印日志。为此,我在一个名为custom_logger.py的文件中定义了decorator:无法使用python中其他文件中定义的装饰器,python,python-decorators,Python,Python Decorators,我正在尝试使用decorator打印日志。为此,我在一个名为custom_logger.py的文件中定义了decorator: import logging class Logger(object): def __init__(self,decoratee_enclosing_class): self.decoratee_enclosing_class = decoratee_enclosing_class def __call__(self, aFunc):
import logging
class Logger(object):
def __init__(self,decoratee_enclosing_class):
self.decoratee_enclosing_class = decoratee_enclosing_class
def __call__(self, aFunc):
"""Trace entry, exit and exceptions."""
def loggedFunc( *args, **kw ):
print "enter", aFunc.__name__
try:
result= aFunc( *args, **kw )
except Exception, e:
print "exception", aFunc.__name__, e
raise
print "exit", aFunc.__name__
return result
loggedFunc.__name__= aFunc.__name__
loggedFunc.__doc__= aFunc.__doc__
return loggedFunc
下面是我的示例测试代码:
from custom_logger import Logger
class Test(object):
@Logger('Test')
def testP(self):
print "hello"
a = Test()
a.testP()
我遇到以下错误:
回溯(最近一次呼叫最后一次):
文件“test.py”,第13行,在
a、 testP()
TypeError:“非类型”对象不可调用
有人能指出我遗漏了什么吗
我已经跟随这个链接好几年了。您的装饰程序中有一个缩进错误。
\u call\u
方法的最后三行应该与def loggedFunc
行位于同一缩进处。第一个代码块中的最后三行应该以一个级别进行缩进。decoree\u封装类的意义是什么?为什么要将类名作为方法装饰器的参数?另外,除了例外,e:
在这一点上是一种非常老式的语法,在Python3.x上不起作用。@jornsharpe感谢您指出。。。但这只是我尝试的示例代码。