gpt4 book ai didi

python - 类型错误 : __class__ assignment only supported for heap types or ModuleType subclasses

转载 作者:太空宇宙 更新时间:2023-11-03 12:54:08 29 4
gpt4 key购买 nike

我正在尝试将函数从任意“基”类复制到我的新对象中。但是,此示例代码出现以下错误。

class my_base:
def print_hey():
print("HEY")

def get_one():
print(1)

class my_ext:
def __init__(self, base):
methods = [method for method in dir(base) if callable(getattr(base, method))]
for method in methods:
setattr(self, method, getattr(base, method))


me = my_ext(my_base)
me.get_one()

以上代码在调用 setattr 时出现此错误。

 TypeError: __class__ assignment only supported for heap types or ModuleType subclasses

如果我在定义上述内容后将其输入到提示中,则该语句有效。

最佳答案

这里的问题是python中的所有对象都有一个__class__属性来存储对象的类型:

>>> my_base.__class__
<class 'type'>
>>> type(my_base)
<class 'type'>

由于调用类是创建该类实例的方式,因此它们被视为可调用对象并传递 callable测试:

>>> callable(my_base)
True
>>> my_base()
<__main__.my_base object at 0x7f2ea5304208>

当您的代码尝试将某些内容分配给 __class__ 属性时,您观察到的 TypeError 将被抛出:

>>> object().__class__ = int
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __class__ assignment only supported for heap types or ModuleType subclasses

因此您需要更具体地说明应复制哪些属性。

您可以过滤掉带有双下划线的属性:

methods = [method for method in dir(base) if not method.startswith('__')
and callable(getattr(base, method))]

或者您可以过滤掉类:

methods = [method for method in dir(base) if callable(getattr(base, method)) and
not isinstance(getattr(base, method), type)]

或者您只能通过与 types.FunctionType 进行比较来允许函数:

methods = [method for method in dir(base) if callable(getattr(base, method)) and
isinstance(getattr(base, method), types.FunctionType)]

关于python - 类型错误 : __class__ assignment only supported for heap types or ModuleType subclasses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49718703/

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