旧式类中的“super”¶
ID: py/super-in-old-style
Kind: problem
Security severity:
Severity: error
Precision: very-high
Tags:
- portability
- correctness
Query suites:
- python-security-and-quality.qls
仅新式类支持使用super()
访问在类中被覆盖的继承方法的功能。当您在旧式类中使用super()
函数时,它会失败。
建议¶
如果您想使用super()
内置函数访问继承方法,那么请确保该类是新式类。您可以通过继承object
将旧式类转换为新式类。或者,您可以从旧式类中直接调用超类的__init__
方法,方法是:BaseClass.__init__(...)
。
示例¶
在以下示例中,PythonModule
是一个旧式类,因为它继承自另一个旧式类。如果_ModuleIteratorHelper
类无法转换为新式类,则必须替换对super()
的调用。PythonModule2
类演示了从旧式类中正确调用超类的示例。
class PythonModule(_ModuleIteratorHelper): # '_ModuleIteratorHelper' and 'PythonModule' are old-style classes
# class definitions ....
def walkModules(self, importPackages=False):
if importPackages and self.isPackage():
self.load()
return super(PythonModule, self).walkModules(importPackages=importPackages) # super() will fail
class PythonModule2(_ModuleIteratorHelper): # call to super replaced with direct call to class
# class definitions ....
def walkModules(self, importPackages=False):
if importPackages and self.isPackage():
self.load()
return _ModuleIteratorHelper.__init__(PythonModule, self).walkModules(importPackages=importPackages)