gpt4 book ai didi

python - 如何装饰父类并让子类使用它? Python

转载 作者:行者123 更新时间:2023-11-28 18:45:04 27 4
gpt4 key购买 nike

我想要的是创建一个类装饰器来装饰一个类并在子类上工作。

想象一下这个类:

class CustomBaseTest(TransactionTestCase):
def __init__(self, *args, **kwargs):
...

def more_custom_helpers(self):
...

和真正的测试:

class FooTest(CustomBaseTest):
def decorate_this_foo_is_ok(self):
....

def decorate_this_fails(self):
...

我想要的是在 CustomBaseTest 中使用一个装饰器,它可以找到所有以“decoratte_this_”开头的方法,并在之后和之前执行自定义代码。我已经有了装饰器,像这样:

def class_decorator(klass):
is_method_test = lambda m: not m.startswith('_') and m.startswith('decorate_this_') and isinstance(getattr(klass, m), MethodType)
test_methods = filter(is_method_test, dir(klass))

for method_name in test_methods:
class_method = getattr(klass, method_name)

def helper(mname, method):
@wraps(method)
... some logic here
retval = method(*a, **kw)
... more logic here
return retval
return wrapper

fn = MethodType(helper(method_name, class_method), None, klass)
setattr(klass, method_name, fn)
return klass

你知道这样做是否可行吗?以及如何?

谢谢!!!

最佳答案

感谢@Markku@BrenBarn .

这是解决方案。

首先我们有一个简单的装饰器:

from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# do some stuff
retval = func(*args, **kwargs)
# do more stuff
return retval
return wrapper

元类:

class ProfileMetaByClass(type):
def __init__(cls, name, bases, dct):
for method_name, method in dct.items():
if method_name.startswith('decorate_this_'):
setattr(cls, method_name, my_decorator(method))
type.__init__(cls, name, bases, dct)

这对我有用!

关于python - 如何装饰父类并让子类使用它? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21585945/

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