gpt4 book ai didi

python - Pypy 特定错误

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:45 24 4
gpt4 key购买 nike

我有以下代码:

#!/usr/bin/env python
#!/usr/bin/env pypy

class my_components(object):
COMP0 = 0
COMP1 = 1
COMP1 = 2
__IGNORECOMP = -1

def attribute_dictionary(o):
d = { }
for attr in dir(o):
if attr[:2] != '__':
print o,attr
d[attr] = o.__getattribute__(o, attr)
return d

def main():
print attribute_dictionary(my_components)

if __name__ == '__main__':
main()

我用它来有效地在 python 中进行花哨的枚举。

它在 python 中运行良好,打印:

<class '__main__.my_components'> COMP0
<class '__main__.my_components'> COMP1
<class '__main__.my_components'> _my_components__IGNORECOMP
{'COMP0': 0, 'COMP1': 2, '_my_components__IGNORECOMP': -1}

但是,当我用 pypy 运行它时(切换前两行)它失败了:

<class '__main__.my_components'> COMP0
Traceback (most recent call last):
File "app_main.py", line 53, in run_toplevel
File "./pypy_Test.py", line 25, in <module>
main()
File "./pypy_Test.py", line 21, in main
print attribute_dictionary(my_components)
File "./pypy_Test.py", line 17, in attribute_dictionary
d[attr] = o.__getattribute__(o, attr)
TypeError: unbound method __getattribute__() must be called with my_components instance as first argument (got type instance instead)

欢迎任何见解。

-谢谢

最佳答案

您正在调用 __getattribute__ 并传入 ,而不是该类的实例。来自__getattribute__ documentation :

Called unconditionally to implement attribute accesses for instances of the class.

事实上,在 cPython 中,类作为第一个参数完全有效,这是一个快乐的巧合;正式地,第一个参数应该是一个实例。

关于python - Pypy 特定错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13886415/

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