为什么属性装饰器显示“对象没有属性”?

时间:2013-03-11 20:49:39

标签: python pyqt4 python-decorators

我有以下代码:

import sys
import platform
from PyQt4.QtGui import QApplication
from PyQt4.QtWebKit import QWebPage

class Render(QWebPage):
    def __init__(self):
        self.app = QApplication([])
        QWebPage.__init__(self)

    @property
    def html(self):
        return self.mainFrame().toHtml.toAscii()

page = Render()
print sys.version, platform.platform()
print 'html attribute?', [p for p in dir(page) if 'html' in p]
print page.html

给出了这个异常输出:

stav@maia:$ python property.py
2.7.3 (default, Aug  1 2012, 05:14:39)
[GCC 4.6.3] Linux-3.2.0-38-generic-x86_64-with-Ubuntu-12.04-precise
html attribute? ['html']
Traceback (most recent call last):
  File "property.py", line 18, in <module>
    print page.html
AttributeError: 'Render' object has no attribute 'html'

如果我删除@property装饰器或删除.toAscii电话,那么它可以正常工作。但是为什么错误说即使dir(page)显示它也没有属性?

2 个答案:

答案 0 :(得分:6)

这里的问题是Python提供了一个误导性的错误消息。在这种情况下,人们期望的错误信息是:

AttributeError: 'function' object has no attribute 'toAscii'

但相反,Python给出了一个误导性错误消息:

AttributeError: 'Render' object has no attribute 'html'

也就是说,在属性函数中生成了AttributeError ,就好像它是属性本身的AttributeError一样。

当您@property的课程来自QObject时,会发生这种奇怪的行为。这是PyQt中的一个已知问题。事实上,PyQt维护者声称它是预期的行为(错误地,恕我直言)。有关详细信息,请参阅this thread。 (在该线程中,声称QObject的行为与Python的内置object类相同,但我自己的测试表明不是这样。)

答案 1 :(得分:1)

你可能意味着.toHtml().toAscii()。请注意缺少的括号。