重写方法的签名和使用不匹配¶
ID: py/inheritance/incorrect-overridden-signature
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- maintainability
Query suites:
- python-security-and-quality.qls
对重写方法的调用,以及可能对重写方法的调用,使用对重写方法而言不合法参数。如果调用了重写方法,这将导致错误,并且违反了 Liskov 替换原则。
建议¶
确保重写方法接受对重写方法(或方法)而言合法的所有参数。
示例¶
在本示例中,基类方法 (self, source, filename)
和扩展方法 (self, source)
的合法参数之间存在不匹配。由于存在使用扩展方法签名的调用,因此可以推断出基签名存在错误,并且应该更新为与扩展方法签名匹配。
class BaseClass(object):
def run(self, source, filename, symbol="single"):
... # Definition
def load_and_run(self, filename):
source = self.load(filename)
self.run(source) # Matches signature in derived class, but not in this class.
class DerivedClass(BaseClass):
def run(self, source):
... # Definition
基方法应该更新为要么删除 filename
参数,要么为其添加默认值。
参考资料¶
维基百科: Liskov 替换原则,方法重写。