【发布时间】:2016-02-17 04:23:27
【问题描述】:
这是我的 Python 代码。我有一个类MyClass 有两个静态方法:my_method1 和my_method2。这两种方法都使用名为 exception_handler 的装饰器包装。
from functools import wraps
import sys
def exception_handler(function):
@wraps(function)
def decorator(self, *args, **kwargs):
try:
return function(self, *args, **kwargs)
except Exception, e:
print "EXCEPTION!: %s" % e
sys.exit(-1)
return decorator
class MyClass:
@staticmethod
@exception_handler
def my_method1(a, b, c,):
return "X"
@staticmethod
@exception_handler
def my_method2(e, f, g,):
print "Y"
return MyClass.my_method1(a=e, b=f, c=g)
print "Trying my_method1"
print MyClass.my_method1(1, 2, 3)
print ""
print "Trying my_method2"
print MyClass.my_method2(1, 2, 3)
当我运行这段代码时,我得到以下信息:
Trying my_method1
X
Trying my_method2
Y
EXCEPTION!: decorator() takes at least 1 argument (0 given)
为什么装饰器在第二种情况下会失败,我该如何解决?
当装饰方法是被另一个静态方法调用的静态方法时,装饰器似乎失败了。但是为什么会发生这种情况对我来说毫无意义。
【问题讨论】:
-
为什么内部函数中有一个“自我”?静态方法不会将 self 或 cls 作为第一个参数
-
except Exception, e::如果可能,请使用except Exception as e:。这个语法一直是deprecated since Python 2.6。 -
奥兹。此装饰器旨在用于静态方法和非静态类方法。它对两者都有效......直到我尝试从另一个包装的静态方法中调用一个包装的静态方法。
-
感谢 Evert 指出这一点。我会做出改变。
标签: python static-methods python-decorators