不一致的方法解析顺序¶
ID: py/inconsistent-mro
Kind: problem
Security severity:
Severity: error
Precision: very-high
Tags:
- reliability
- correctness
Query suites:
- python-security-and-quality.qls
Python 2.3 引入了新式类(继承自 object 的类)。新式类使用 C3 线性化方法来确定每个类的“方法解析顺序”(MRO)。C3 线性化方法确保,对于类 C,如果类 C1 在 C 的 MRO 中优先于类 C2,则 C1 也应该在 C 的所有子类的 MRO 中优先于 C2。有可能创建一种情况,在这种情况下,无法实现这种一致性,这将保证在运行时引发 TypeError
。
建议¶
使用不含歧义的类层次结构。
示例¶
类 X
的 MRO 只是 X, object
。当需要计算类 Y
的 MRO 时,程序将失败,因为 object
在 Y
的定义中优先于 X
,但在 X
的 MRO 中则相反。
class X(object):
def __init__(self):
print("X")
class Y(object,X):
def __init__(self):
print("Y")
参考¶
Python: Python 2.3 方法解析顺序。