TypeError:__class__赋值仅支持堆类型或ModuleType子类 [英] TypeError: __class__ assignment only supported for heap types or ModuleType subclasses
问题描述
我正在尝试将函数从任意基"类复制到新对象中.但是,此示例代码出现以下错误.
I'm trying to copy functions from an arbitrary 'base' class into my new object. However, I'm getting the following error with this sample code.
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
时出现此错误.
The above gets this error on the call to setattr
.
TypeError: __class__ assignment only supported for heap types or ModuleType subclasses
如果在定义完上述内容后在提示中键入该语句,该语句将起作用.
The statement works if I type it into the prompt after defining the above.
推荐答案
这里的问题是python中的所有对象都有一个__class__
属性,该属性存储对象的类型:
The problem here is that all objects in python have a __class__
attribute that stores the type of the object:
>>> my_base.__class__
<class 'type'>
>>> type(my_base)
<class 'type'>
由于调用类是您创建该类实例的方式,因此它们被视为可调用对象,并传递 callable
测试:
Since calling a class is how you create an instance of that class, they're considered callables and pass the callable
test:
>>> callable(my_base)
True
>>> my_base()
<__main__.my_base object at 0x7f2ea5304208>
当您的代码尝试将某些内容分配给__class__
属性时,将抛出您观察到的TypeError:
And when your code tries to assign something to the __class__
attribute the TypeError you've observed is thrown:
>>> 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
因此,您需要更具体地说明应复制哪些属性.
So you need to be more specific about which attributes should be copied.
您可以过滤带有双下划线的属性:
You could filter out attributes with double underscores:
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
:
Or you could only allow functions by comparing to types.FunctionType
:
methods = [method for method in dir(base) if callable(getattr(base, method)) and
isinstance(getattr(base, method), types.FunctionType)]
这篇关于TypeError:__class__赋值仅支持堆类型或ModuleType子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!