下面的代码应该会打印相同的内容三次。为什么没有呢?
QObject的元类甚至没有覆盖getattribute方法,那么为什么我用"cls.instance"却拿不到A实例呢?更奇怪的是,在赋值之前不访问该属性(请参见注释掉的代码行)就可以正常工作。我可以通过以下方式重现此问题(使用PySide 1.1.0):Windows 7 64位,Python 2.7.1 32位:正常工作;Windows 7 64位,Python 2.7.3 32位:正常工作;Windows 7 64位,Python 3.2.3 32位:失败;Ubuntu 11.10 64位,Python 2.7.2+:正常工作;Ubuntu 11.10 64位,Python 3.2.2:失败。更新:我成功在Ubuntu上编译了PySide 1.1.1和Python 3.2.2,但它并没有解决这个问题。
from PySide.QtCore import QObject
class A(QObject):
instance = 1
@classmethod
def test(cls):
cls.instance # Remove this line and it prints the right thing
cls.instance = cls()
print(cls.__dict__['instance'])
print(cls.instance)
print(type.__getattribute__(cls, 'instance'))
A.test()
期望的结果:
<__main__.A object at 0x1310c20>
<__main__.A object at 0x1310c20>
<__main__.A object at 0x1310c20>
实际结果:
<__main__.A object at 0x2242878>
1
1
QObject的元类甚至没有覆盖getattribute方法,那么为什么我用"cls.instance"却拿不到A实例呢?更奇怪的是,在赋值之前不访问该属性(请参见注释掉的代码行)就可以正常工作。我可以通过以下方式重现此问题(使用PySide 1.1.0):Windows 7 64位,Python 2.7.1 32位:正常工作;Windows 7 64位,Python 2.7.3 32位:正常工作;Windows 7 64位,Python 3.2.3 32位:失败;Ubuntu 11.10 64位,Python 2.7.2+:正常工作;Ubuntu 11.10 64位,Python 3.2.2:失败。更新:我成功在Ubuntu上编译了PySide 1.1.1和Python 3.2.2,但它并没有解决这个问题。