!87 增加python通用编码规则3.6特殊方法应该有预期数量的参数
Merge pull request !87 from xujian/master
This commit is contained in:
commit
2809a58465
|
@ -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等)使得控制流程跳出当前代码块,跳转后的语句可能是死代码。应该删除不可达的死代码。
|
||||
|
|
Loading…
Reference in New Issue