gpt4 book ai didi

python - 从装饰器访问拥有装饰方法的类

转载 作者:太空狗 更新时间:2023-10-30 01:52:35 26 4
gpt4 key购买 nike

我正在为必须检查父方法(我正在装饰的类的父类中同名的方法)的方法编写装饰器。

示例(来自 PEP 318 的第四个示例):

def returns(rtype):
def check_returns(f):
def new_f(*args, **kwds):
result = f(*args, **kwds)
assert isinstance(result, rtype), \
"return value %r does not match %s" % (result,rtype)
return result
new_f.func_name = f.func_name
# here I want to reach the class owning the decorated method f,
# it should give me the class A
return new_f
return check_returns

class A(object):
@returns(int)
def compute(self, value):
return value * 3

所以我正在寻找代码来代替 # here I want...

谢谢。

最佳答案

作为bobince said it ,您不能访问周围的类,因为在调用装饰器时,该类还不存在。如果您需要访问类和基础的完整字典,您应该考虑 metaclass :

__metaclass__

This variable can be any callable accepting arguments for name, bases, and dict. Upon class creation, the callable is used instead of the built-in type().

基本上,我们将 returns 装饰器转换为仅告诉元类在类构造上做一些魔术的东西:

class CheckedReturnType(object):
def __init__(self, meth, rtype):
self.meth = meth
self.rtype = rtype

def returns(rtype):
def _inner(f):
return CheckedReturnType(f, rtype)
return _inner

class BaseInspector(type):
def __new__(mcs, name, bases, dct):
for obj_name, obj in dct.iteritems():
if isinstance(obj, CheckedReturnType):
# do your wrapping & checking here, base classes are in bases
# reassign to dct
return type.__new__(mcs, name, bases, dct)

class A(object):
__metaclass__ = BaseInspector
@returns(int)
def compute(self, value):
return value * 3

注意我还没有测试过这段代码,如果我应该更新这个请留下评论。

有一些articles on metaclasses由非常值得推荐的 David Mertz 撰写,在这种情况下您可能会发现它很有趣。

关于python - 从装饰器访问拥有装饰方法的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/753537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com