【发布时间】:2018-09-18 00:16:33
【问题描述】:
我正在尝试将任意“基”类中的函数复制到我的新对象中。但是,此示例代码出现以下错误。
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
如果我在定义上述内容后将其键入提示符,则该语句有效。
【问题讨论】:
-
看来 getattr() 返回的所有属性都被认为是可调用的。所以第一个
__class__是导致此错误的原因。也许还有其他方法可以判断一个属性是否是一个函数? -
你为什么要这样做?为什么不继承 my_base?
-
即使我们修复了 TypeError,代码仍然无法工作,因为您正在向实例添加未绑定的方法。真的,你为什么要这样做?这看起来不像是干净的代码。
-
在这个设计中有充分的理由这样做。这不是真正的问题。
-
@Aran-Fey 向这样的实例添加方法完全没问题。这是一种动态语言,并且动态发生。