CodeQL 文档

在超类或子类中覆盖属性

ID: py/overwritten-inherited-attribute
Kind: problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - reliability
   - maintainability
   - modularity
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

子类不应该设置在超类中设置的属性。这样做可能会违反超类中的不变式。

建议

如果你没有打算覆盖超类中设置的属性值,那么重命名子类属性。如果你确实想要能够为超类的属性设置一个新值,那么将超类属性转换为属性。否则,应该将该值作为参数传递给超类的 __init__ 方法。

示例


#Attribute set in both superclass and subclass
class C(object):

    def __init__(self):
        self.var = 0

class D(C):

    def __init__(self):
        self.var = 1 # self.var will be overwritten
        C.__init__(self)

class E(object):

    def __init__(self):
        self.var = 0 # self.var will be overwritten

class F(E):

    def __init__(self):
        E.__init__(self)
        self.var = 1

#Fixed version -- Pass explicitly as a parameter
class G(object):

    def __init__(self, var = 0):
        self.var = var

class H(G):

    def __init__(self):
        G.__init__(self, 1)

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