CodeQL 文档

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

点击查看 CodeQL 代码库中的查询

应使用封闭类作为 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()
        

参考

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