Pypy指定

2024-09-23 06:38:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

#!/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中有效地执行花哨的enum。你知道吗

它在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)

任何见解都是最受欢迎的。你知道吗

-谢谢


Tags: inpydictionarymainmylinecomponentsattribute
2条回答

调用__getattribute__传递的是,而不是该类的实例。从^{} documentation

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

事实上,在cPython中,这个类作为第一个参数是有效的,这是一个令人高兴的巧合;正式地说,第一个参数应该是一个实例。你知道吗

TypeError: unbound method __getattribute__() must be called with my_components instance as first argument (got type instance instead)

这意味着(至少在PyPy中,__getattribute__的第一个参数必须是类my_components的实例。你知道吗

相反,o是类my_components本身,而不是实例。你知道吗

尝试改变

d[attr] = o.__getattribute__(o, attr)

d[attr] = getattr(o, attr)

相关问题 更多 >