Search code examples
pythoninheritanceclass-variables

Can I remove an inherited nested class from a python class?


E.g. is this possible?

class Foo(object):
    class Meta:
        pass

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

Solution

  • You cannot remove class attributes from an inherited base class; you can only mask them, by setting an instance variable with the same name:

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

    Your own class could of course also override it with a class variable:

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