CodeQL 文档

重写方法的签名和使用不匹配

ID: py/inheritance/incorrect-overriding-signature
Kind: problem
Security severity: 
Severity: error
Precision: high
Tags:
   - maintainability
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

对重写方法的调用(可能包括覆盖方法)使用了对于覆盖方法而言不合法参数。如果调用覆盖方法,这会导致错误,并且违反了里氏替换原则。

建议

确保覆盖方法接受对重写方法而言合法的所有参数。

示例

在本例中,基类方法 (self, source, filename, symbol) 和扩展方法 (self, source) 之间存在合法参数的不匹配。只要没有为 filename 和(可选)symbol 参数指定值,扩展方法就可以用来覆盖基方法。如果扩展方法传递了基方法所接受的额外参数,则会发生错误。


class BaseClass(object):

    def run(self, source, filename, symbol="single"):
        ... # Definition

    def load_and_run(self, filename):
        source = self.load(filename)
        self.run(source, filename) # Matches signature in this class, but not in the derived class.

class DerivedClass(BaseClass):

    def run(self, source):
        ... # Definition

应该更新扩展方法以支持重写方法所支持的 filenamesymbol 参数。

参考文献

  • ©GitHub, Inc.
  • 条款
  • 隐私