CodeQL 文档

特殊方法签名不正确

ID: py/special-method-wrong-signature
Kind: problem
Security severity: 
Severity: error
Precision: high
Tags:
   - reliability
   - correctness
Query suites:
   - python-security-and-quality.qls

单击以查看 CodeQL 代码库中的查询

特殊方法(有时也称为魔术方法)是用户定义类与 Python 虚拟机交互的方式。例如,要使类支持加法,它必须实现 __add____radd__ 特殊方法。当表达式 a + b 被求值时,Python 虚拟机将调用 type(a).__add__(a, b),如果未实现,它将调用 type(b).__radd__(b, a)

由于这些特殊方法始终由虚拟机使用固定数量的参数调用,如果该方法使用不同数量的参数实现,则它将在运行时使用 TypeError 失败。

建议

确保该方法具有正确数量的参数

示例

在此示例中,__str__ 方法有一个额外的参数。这意味着如果 str(p)pPoint 时被调用,则它将使用 TypeError 失败。

#-*- coding: utf-8 -*-

class Point(object):

    def __init__(self, x, y):
        self.x
        self.y

    def __add__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return Point(self.x + other.x, self.y + other.y)

    def __str__(self, style): #Spurious extra parameter
        if style == 'polar':
            u"%s @ %s\u00b0" % (abs(self), self.angle())
        else:
            return "[%s, %s]" % (self.x, self.y)

参考

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