super() 的第一个参数不是封闭类¶
ID: py/super-not-enclosing-class
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- reliability
- maintainability
- convention
- external/cwe/cwe-687
Query suites:
- python-security-and-quality.qls
应使用封闭类作为 super
类的第一个参数,并使用 self
作为第二个参数。
传递不同的类可能可以正常工作,前提是传递的类是封闭类的超类,并且封闭类没有定义 __init__
方法。但是,如果封闭类稍后使用多重继承进行子类化,这可能会导致对象初始化不正确。
建议¶
确保 super()
的第一个参数是封闭类。
示例¶
在此示例中,在 Car.__init__
中对 super(Vehicle, self)
的调用是错误的,因为它传递了 Vehicle
而不是 Car
作为 super
的第一个参数。因此,在 SportsCar.__init__
方法中,super(SportsCar, self).__init__()
将不会调用所有 __init__()
方法,因为对 super(Vehicle, self).__init__()
的调用跳过了 StatusSymbol.__init__()
。
class Vehicle(object):
pass
class Car(Vehicle):
def __init__(self):
#This is OK provided that Car is not subclassed.
super(Vehicle, self).__init__()
self.car_init()
class StatusSymbol(object):
def __init__(self):
super(StatusSymbol, self).__init__()
self.show_off()
class SportsCar(Car, StatusSymbol):
def __init__(self):
#This will not call StatusSymbol.__init__()
super(SportsCar, self).__init__()
self.sports_car_init()
#Fix Car by passing Car to super().
#SportsCar does not need to be changed.
class Car(Car, Vehicle):
def __init__(self):
super(Car, self).__init__()
self.car_init()
参考¶
Python 标准库:super.
Artima 开发者:关于 Python super 的一些知识.
常见漏洞枚举:CWE-687.