假设我创建了一个具有属性的常规Python类,并且在该属性的实现中我犯了一个导致AttributeError的错误。 MVCE如下:
class MyClass():
@property
def myProp(self):
raise AttributeError("my mistake")
def main():
# Gives a 'expected-error-message' as expected
myObject = MyClass()
print("Regular object property: {}".format(myObject.myProp))
if __name__ == "__main__":
main()
这会出现以下错误,如预期的那样:
Traceback (most recent call last):
File "prop_regular.py", line 14, in <module>
main()
File "prop_regular.py", line 10, in main
print("Regular object property: {}".format(myObject.myProp))
File "prop_regular.py", line 5, in myProp
raise AttributeError("my mistake")
AttributeError: my mistake
但是,如果我让该类继承自QObject,则错误令人困惑。例如,运行以下代码
from PyQt5 import QtCore
class MyQtClass(QtCore.QObject):
@property
def myProp(self):
raise AttributeError("my-mistake")
def main():
app = QtCore.QCoreApplication([])
# Gives confusing error message: 'MyQtClass' object has no attribute 'myProp'
qc = MyQtClass()
print("Qt object property: {}".format(qc.myProp))
if __name__ == "__main__":
main()
给出
Traceback (most recent call last):
File "prop_qt.py", line 19, in <module>
main()
File "prop_qt.py", line 15, in main
print("Qt object property: {}".format(qc.myProp))
AttributeError: 'MyQtClass' object has no attribute 'myProp'
但是MyQtClass
类确实具有myProp
属性,它只包含一个错误!我花了一些时间在一个真实的应用程序中进行调试。
所以我的问题是:这里发生了什么?这是PyQt中的错误吗?或者我做错了什么?
修改
Ekhumoro的回答促使我查看PyQt(5.6)来源。似乎错误源自QtCore/qpycore_qobject_getattr.cpp
,它定义了以下函数
// See if we can find an attribute in the Qt meta-type system. This is
// primarily to support access to JavaScript (e.g. QQuickItem) so we don't
// support overloads.
PyObject *qpycore_qobject_getattr(const QObject *qobj, PyObject *py_qobj,
const char *name)
{
const QMetaObject *mo = qobj->metaObject();
// Try and find a method with the name.
QMetaMethod method;
int method_index = -1;
// Count down to allow overrides (assuming they are possible).
for (int m = mo->methodCount() - 1; m >= 0; --m)
{
method = mo->method(m);
if (method.methodType() == QMetaMethod::Constructor)
continue;
// Get the method name.
QByteArray mname(method.methodSignature());
int idx = mname.indexOf('(');
if (idx >= 0)
mname.truncate(idx);
if (mname == name)
{
method_index = m;
break;
}
}
if (method_index >= 0)
{
// Get the value to return. Note that this is recreated each time. We
// could put a descriptor in the type dictionary to satisfy the request
// in future but the typical use case is getting a value from a C++
// proxy (e.g. QDeclarativeItem) and we can't assume that what is being
// proxied is the same each time.
if (method.methodType() == QMetaMethod::Signal)
{
// We need to keep explicit references to the unbound signals
// (because we don't use the type dictionary to do so) because they
// own the parsed signature which may be needed by a PyQtSlotProxy
// at some point.
typedef QHash<QByteArray, PyObject *> SignalHash;
static SignalHash *sig_hash = 0;
// For crappy compilers.
if (!sig_hash)
sig_hash = new SignalHash;
PyObject *sig_obj;
QByteArray sig_str = method.methodSignature();
SignalHash::const_iterator it = sig_hash->find(sig_str);
if (it == sig_hash->end())
{
sig_obj = (PyObject *)qpycore_pyqtSignal_New(
sig_str.constData());
if (!sig_obj)
return 0;
sig_hash->insert(sig_str, sig_obj);
}
else
{
sig_obj = it.value();
}
return qpycore_pyqtBoundSignal_New((qpycore_pyqtSignal *)sig_obj,
py_qobj, const_cast<QObject *>(qobj));
}
// Respect the 'private' nature of __ names.
if (name[0] != '_' || name[1] != '_')
{
QByteArray py_name(Py_TYPE(py_qobj)->tp_name);
py_name.append('.');
py_name.append(name);
return qpycore_pyqtMethodProxy_New(const_cast<QObject *>(qobj),
method_index, py_name);
}
}
// Replicate the standard Python exception.
PyErr_Format(PyExc_AttributeError, "'%s' object has no attribute '%s'",
Py_TYPE(py_qobj)->tp_name, name);
return 0;
}
如果在Qt元类型系统中找不到该名称的方法,则会引发该错误消息。我想确实很难做其他事情。
答案 0 :(得分:1)
当一个类定义__getattr__
时,这是normal python behaviour,因为只要AttributeError
被引发就必须调用:
>>> class MyClass():
... @property
... def myProp(self):
... raise AttributeError("my mistake")
... def __getattr__(self, name):
... raise AttributeError("no attribute %r" % name)
...
>>> x = MyClass()
>>> x.myProp
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __getattr__
AttributeError: no attribute 'myProp'
如果没有定义__getattr__
,则传播原始异常;否则,吞下原文并改为__getattr__
引发的异常。
这意味着从QObject
派生的所有PyQt类都必须定义__getattr__
。