我不明白为什么这个程序失败了。
#!/usr/bin/env python
from __future__ import division, print_function
from future_builtins import *
import types
import libui as ui
from PyQt4 import QtCore
import sip
p = ui.QPoint()
q = QtCore.QPoint()
def _q_getattr(self, attr):
print("get %s" % attr)
value = getattr(sip.wrapinstance(self.myself(), QtCore.QPoint), attr)
print("get2 %s returned %s" % (attr, value))
return value
p.__getattr__ = types.MethodType(_q_getattr, p)
print(p.__getattr__('x')()) # Works! Prints "0"
print(p.x()) # AttributeError: 'QPoint' object has no attribute 'x'
我使用 Boost.Python 创建 libui,它公开了 QPoint 类。我还包含了 PyQt4,它有一个 sip 暴露的 QPoint。我正在尝试完成两种类型之间的映射。
我查了一下p
是一个新式的类,为什么不呢__getattr__
被召唤p.x()
?
这和这个问题有些相似别人遇到过就在昨天。简而言之,这似乎是特殊的方法(比如__getattr__
, __str__
, __repr__
, __call__
等等)在新式类中是不可重写的instance,即您只能在其类型中定义它们。
这是我针对该问题的解决方案的改编,希望对您有用:
def _q_getattr(self, attr):
print("get %s" % attr)
return getattr(self, 'x')
def override(p, methods):
oldType = type(p)
newType = type(oldType.__name__ + "_Override", (oldType,), methods)
p.__class__ = newType
override(p, { '__getattr__': _q_getattr})
print(p.__getattr__('x')()) # Works! Prints "0"
print(p.x()) # Should work!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)