【发布时间】:2021-12-31 10:27:48
【问题描述】:
我正在尝试创建一个可以在类上定义并装饰其中定义的所有内容的装饰器。首先让我展示一下我已经根据其他 SO 答案获得的设置:
import inspect
# https://stackoverflow.com/a/18421294/577669
def log(func):
def wrapped(*args, **kwargs):
try:
print("Entering: [%s]" % func)
try:
# https://stackoverflow.com/questions/19227724/check-if-a-function-uses-classmethod
if inspect.ismethod(func) and func.__self__: # class method
return func(*args[1:], **kwargs)
if inspect.isdatadescriptor(func):
return func.fget(args[0])
return func(*args, **kwargs)
except Exception as e:
print('Exception in %s : (%s) %s' % (func, e.__class__.__name__, e))
finally:
print("Exiting: [%s]" % func)
return wrapped
class trace(object):
def __call__(self, cls): # instance, owner):
for name, m in inspect.getmembers(cls, lambda x: inspect.ismethod(x) or inspect.isfunction(x)):
setattr(cls, name, log(m))
for name, m in inspect.getmembers(cls, lambda x: inspect.isdatadescriptor(x)):
setattr(cls, name, property(log(m)))
return cls
@trace()
class Test:
def __init__(self, arg):
self.arg = arg
@staticmethod
def static_method(arg):
return f'static: {arg}'
@classmethod
def class_method(cls, arg):
return f'class: {arg}'
@property
def myprop(self):
return 'myprop'
def normal(self, arg):
return f'normal: {arg}'
if __name__ == '__main__':
test = Test(1)
print(test.arg)
print(test.static_method(2))
print(test.class_method(3))
print(test.myprop)
print(test.normal(4))
当从类中移除 @trace 装饰器时,输出如下:
123
static
class
myprop
normal
当添加 @trace 装饰器时,我得到了这个:
Entering: [<function Test.__init__ at 0x00000170FA9ED558>]
Exiting: [<function Test.__init__ at 0x00000170FA9ED558>]
1
Entering: [<function Test.static_method at 0x00000170FB308288>]
Exception in <function Test.static_method at 0x00000170FB308288> : (TypeError) static_method() takes 1 positional argument but 2 were given
Exiting: [<function Test.static_method at 0x00000170FB308288>]
None
Entering: [<bound method Test.class_method of <class '__main__.Test'>>]
Exiting: [<bound method Test.class_method of <class '__main__.Test'>>]
class: 3
Entering: [<property object at 0x00000170FB303E08>]
Exiting: [<property object at 0x00000170FB303E08>]
myprop
Entering: [<function Test.normal at 0x00000170FB308438>]
Exiting: [<function Test.normal at 0x00000170FB308438>]
normal: 4
此示例的结论:init、normal、class 和 prop 方法都正确检测。
但是,静态方法不是。
我对这个 sn-p 的问题是:
- 可以像我在日志中那样检查某些用例吗?还是有更好的方法?
- 如何查看某个东西是否是静态方法才能不传入任何内容(因为现在传入的是 Test-instance)?
谢谢!
【问题讨论】:
-
测试我的答案,我注意到您的输出与我在您的代码中所期望的不符。您是否更改了一些测试数据?