!87 增加python通用编码规则3.6特殊方法应该有预期数量的参数

Merge pull request !87 from xujian/master
This commit is contained in:
xujian 2023-12-07 07:57:51 +00:00 committed by Gitee
commit 2809a58465
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
1 changed files with 26 additions and 0 deletions

View File

@ -683,6 +683,32 @@ new_exception.__cause__ = chained_exception
[python内置函数-属性](https://docs.python.org/zh-cn/3/library/functions.html#property)
## 规则3.6 特殊方法应该有预期数量的参数(python:S5722)
Python开发人员可以通过定义特殊方法也称为魔术方法来自定义代码的解释方式。例如可以通过在类中定义__mul__和__rmul__方法来覆盖乘法运算符a*b。这样当用这个类执行乘法运算时python解释器就会调用类实现的特殊方法而不是执行默认的乘法方法。python解释器将始终使用相同数量的参数调用这些方法。如果一个自定义的特殊方法使用了不符合预期数量的参数那么对该方法的调用将会失败。当使用不符合预期数量的参数定义特殊方法时此规则会报告问题。
### 错误代码
class A:
def __mul__(self, other, unexpected): # Noncompliant. Too many parameters
return 42
def __add__(self): # Noncompliant. Missing one parameter
return 42
A() * 3 # TypeError: __mul__() missing 1 required positional argument: 'unexpected'
A() + 3 # TypeError: __add__() takes 1 positional argument but 2 were given
### 正确代码
class A:
def __mul__(self, other):
return 42
def __add__(self, other):
return 42
A() * 3
A() + 3
# 4 控制流
## 规则4.1 所有代码都应该是可达的(python:S1763)
当使用了跳转语句return、break、continue和raise等使得控制流程跳出当前代码块跳转后的语句可能是死代码。应该删除不可达的死代码。