11

私は次のコードを持っています:

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)それを示していても属性がないと言うのですか?

4

2 に答える 2

12

ここでの問題は、Pythonが誤解を招くエラーメッセージを表示したことです。この場合に予想されるエラーメッセージは次のとおりです。

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

しかし、代わりに、Pythonは誤解を招くエラーメッセージを出しました:

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

つまり、プロパティ関数内でAttributeError生成されたものは、プロパティ自体の場合と同じように表示されました。AttributeError

この奇妙な振る舞いは、あなたのクラス@propertyがから派生したときに発生しますQObject。これはPyQtの既知の問題です。実際、PyQtのメンテナは、それが予想される動作であると主張しています(間違って、私見)。詳細については、このスレッドを参照してください。QObject(そのスレッドでは、Pythonの組み込みクラスと同じように動作すると主張されobjectていますが、私自身のテストではそうではないことが示されています。)

于 2013-10-31T20:33:23.387 に答える
1

あなたはおそらく意味し.toHtml().toAscii()ました。括弧がないことに注意してください。

于 2013-03-11T21:00:30.393 に答える