我有以下代码:
#!/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)
任何见解都是最受欢迎的。你知道吗
-谢谢
调用} documentation :
__getattribute__
传递的是类,而不是该类的实例。从^{事实上,在cPython中,这个类作为第一个参数是有效的,这是一个令人高兴的巧合;正式地说,第一个参数应该是一个实例。你知道吗
这意味着(至少在PyPy中,
__getattribute__
的第一个参数必须是类my_components
的实例。你知道吗相反,
o
是类my_components
本身,而不是实例。你知道吗尝试改变
至
相关问题 更多 >
编程相关推荐