【问题标题】:Can I remove an inherited nested class from a python class?我可以从 python 类中删除继承的嵌套类吗?
【发布时间】:2012-09-01 04:19:22
【问题描述】:

例如这可能吗?

class Foo(object):
    class Meta:
        pass

class Bar(Foo):
    def __init__(self):
        # remove the Meta class here?
        super(Bar, self).__init__()

【问题讨论】:

    标签: python inheritance class-variables


    【解决方案1】:

    您不能从继承的基类中删除类属性;您只能通过设置同名的实例变量来屏蔽它们:

    class Bar(Foo):
        def __init__(self):
            self.Meta = None  # Set a new instance variable with the same name
            super(Bar, self).__init__()
    

    你自己的类当然也可以用类变量覆盖它:

    class Bar(Foo):
        Meta = None
    
        def __init__(self):
            # Meta is None for *all* instances of Bar.
            super(Bar, self).__init__()
    

    【讨论】:

      【解决方案2】:

      你可以在课堂上做到这一点:

      class Bar(Foo):
          Meta = None
      

      (同样super-调用构造函数是多余的)

      【讨论】:

      • “超调用构造函数是多余的”?不会自动调用父级的 __init__。如果你想调用父级的__init__,你必须明确地这样做。
      • 在他的例子中,他的__init__ 只调用超类的__init__ 而没有别的,如果__init__ 没有在子类中定义(如果我在解释你'说得对。)
      猜你喜欢
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 2018-02-08
      • 2012-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多