gpt4 book ai didi

python - 如何在派生的python类上操作装饰器?

转载 作者:太空宇宙 更新时间:2023-11-03 11:07:09 25 4
gpt4 key购买 nike

我想使用装饰器对派生类做一些事情(例如注册类或其他东西)。这是我的代码:

from functools import wraps

class Basic(object):
def __init__(self):
print "Basic::init"

def myDeco(name):
# define the decorator function that acts on the actual class definition
def __decorator(myclass):

# do something here with the information
print name, myclass

# do the wrapping of the class
@wraps(myclass)
def __wrapper(*args, **kwargs):
return myclass( *args, **kwargs)

# return the actual wrapper here
return __wrapper

# return the decorator to act on the class definition
return __decorator

@myDeco("test")
class Derived(Basic):
def __init__(self):
super(Derived, self).__init__()
print "Derived::init"


instance = Derived()

出现以下错误:

TypeError: must be type, not function

Derived 中的 super 方法被调用时。我假设变量 Derived 不再是 type,而是函数 __decorator

我需要如何更 retrofit 饰器(并且仅更 retrofit 饰器)才能解决此问题?

最佳答案

您正在用函数替换装饰类,因此类定义失败。

具体来说,super(Derived, self).__init__() 现在将一个函数 传递给 super():

>>> super(Derived, object())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be type, not function
>>> type(Derived)
<type 'function'>

类装饰器通常改变类,添加、删除或改变它的属性,然后再次返回类对象。

您应该Derived 替换为新类,因为您的Derived.__init__() 通过名称引用自身。用另一个类替换该名称将导致痛苦(例如无限递归)。

可以工作的类装饰器示例:

def my_deco(name):
# define the decorator function that acts on the actual class definition
def decorator(cls):

# do something here with the information
print name, cls

setattr(class, name, 'Hello world!')

# return the original, augmented class
return cls

# return the decorator to act on the class definition
return decorator

关于python - 如何在派生的python类上操作装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15762855/

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