类型错误:描述符“__weakref__"不适用于来自父 __str__ 方法的对象 [英] TypeError: descriptor '__weakref__' doesn't apply to object from parent __str__ method
问题描述
我有一个父类,我们称之为A
和一堆子类,B
、C
、D
等我想在父类上定义一个 __str__()
方法,在它里面我想通过 dir(self)访问子类的成员代码>.它有效,但是当我使用
callable(getattr(self, attr))
检查名称是否可调用时,我得到:
I have a parent class, let's call it A
and a bunch of child classes, B
, C
, D
, etc. I want to define a single __str__()
method on the parent class and inside it I want to access the members of the child class via dir(self)
. It works, but when I check if the name is a callable with callable(getattr(self, attr))
I get:
TypeError: 'A' 对象的描述符 '__weakref__'
不适用于 'B' 对象
TypeError: descriptor '__weakref__'
for 'A' objects doesn't apply to 'B' object
引发错误的代码是这样的:
The code that raises the error is this:
[attr for attr in dir(self) if not callable(getattr(self, attr)) 而不是 attr.startswith("__")]
谁能解释一下这是什么意思?
Can someone explain what does it mean?
旁注:我设法让所有班级成员通过 self.__dict__
循环,我的问题只是出于好奇,因为我无法理解错误.
Sidenote:
I managed to get all class members cycling through self.__dict__
, my question is just out of curiosity, since I cannot understand the error.
编辑
我做了一个更简单的代码版本:
I made a simpler version of the code:
class A():
def __init__(self):
pass
def test(self, par):
print('10')
def __str__(self):
members = [attr for attr in dir(self) if not callable(getattr(self, attr)) and not attr.startswith("__")]
str = ''
for m in members:
str += m
str += ','
return str
class B(A):
def test_b(self, par):
print('10_b')
def __init__(self,first,second):
self.first = first
self.second = second
if __name__ == '__main__':
b = B('one', 'two')
print(b)
但是这里的代码可以正常工作并正确打印first,second,
But here the code works and correctly prints first,second,
原始代码被打包,A 和 B 的等价物在一个单独的包中,由主"脚本调用.实际代码中该类的 __str__()
方法中的相同代码引发错误.
The original code is packaged, with the equivalent of A and B in a separate package that is called by a "main" script. The same code in the __str__()
method of the class in the actual code raises the error.
推荐答案
您的代码发生了一些非常奇怪的事情.如果有机会发现问题,您将需要提供更多详细信息.您引用的错误仅在一处引发(此处a>) -- 在一种防止来自一个类(如 __weakref__
)的描述符被用于另一种不兼容类型的方法中.
There is something very funky is going on with your code. You'll need to give a lot more detail if there's any chance of finding the problem. The error you reference is raised in one place only (here) -- in a method that protects against descriptors from one class (like __weakref__
) from being used on another incompatible type.
我可以重现错误(并有 B 子类 A)的唯一方法是这样的:
The only way I could reproduce the error (and have B subclass A) was like this:
class A:
pass
class Z:
pass
class B(A,Z):
pass
B.__weakref__.__get__(A()) # works
B.__weakref__.__get__(Z()) # fails
# because
assert B.__weakref__ == A.__weakref__ # is true
assert B.__weakref__ == Z.__weakref__, 'B uses A.__weakref__ rather than Z.__weakref__'
这篇关于类型错误:描述符“__weakref__"不适用于来自父 __str__ 方法的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!