我可以从python类中删除一个继承的嵌套类吗?

时间:2012-09-07 09:32:28

标签: python inheritance class-variables

E.g。这有可能吗?

class Foo(object):
    class Meta:
        pass

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

2 个答案:

答案 0 :(得分:4)

您无法从继承的基类中删除类属性;通过设置具有相同名称的实例变量,您只能掩盖它们:

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__()

答案 1 :(得分:1)

您可以在班级进行:

class Bar(Foo):
    Meta = None

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