gpt4 book ai didi

python - 通过将装饰器定义为类来装饰 Python 中的类

转载 作者:IT老高 更新时间:2023-10-28 21:12:04 26 4
gpt4 key购买 nike

通过将装饰器定义为类来装饰类的简单示例是什么?

我正在尝试使用 PEP 3129 实现 Python 2.6 中已实现的功能除非使用类而不是 Bruce Eckel 解释的函数 here .

以下作品:

class Decorator(object):
def __init__(self, arg):
self.arg = arg

def __call__(self, cls):
def wrappedClass(*args):
return cls(*args)
return type("TestClass", (cls,), dict(newMethod=self.newMethod, classattr=self.arg))

def newMethod(self, value):
return value * 2

@Decorator("decorated class")
class TestClass(object):
def __init__(self):
self.name = "TestClass"
print "init %s"%self.name

def TestMethodInTestClass(self):
print "test method in test class"

def newMethod(self, value):
return value * 3

除了,在上面,wrappedClass 不是一个类,而是一个被操作以返回类类型的函数。我想编写如下相同的可调用对象:

def __call__(self, cls):
class wrappedClass(cls):
def __init__(self):
... some code here ...
return wrappedClass

如何做到这一点?

我不完全确定 """...这里有一些代码..."""

最佳答案

如果你想覆盖 new_method(),就这样做吧:

class Decorator(object):
def __init__(self, arg):
self.arg = arg
def __call__(self, cls):
class Wrapped(cls):
classattr = self.arg
def new_method(self, value):
return value * 2
return Wrapped

@Decorator("decorated class")
class TestClass(object):
def new_method(self, value):
return value * 3

如果您不想更改 __init__(),则无需覆盖它。

关于python - 通过将装饰器定义为类来装饰 Python 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9906144/

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