Making a variable non-inheritable in python

inheritance, python

Solution

If you want to make absolutely sure that subclasses of `A` override `SIZE`, you could use a metaclass for `A` that will raise an error when a subclass does not override it (note that `A` is a new-style class here):

class ClassWithSize(type):
    def __init__(cls, name, bases, attrs):
        if 'SIZE' not in attrs:
            raise NotImplementedError('The "%s" class does not implement a "SIZE" attribute' % name)
        super(ClassWithSize, cls).__init__(name, bases, attrs)

class A(object):
    __metaclass__ = ClassWithSize

    SIZE = 5
    def getsize(self):
        return self.SIZE

class B(A):
    SIZE = 6

class C(A):
    pass

When you put the above in a module and attempt to import it, an exception will be raised when the import reaches the `C` class implementation.

Problem

Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value. Could I get an Error to be raised (on __init__ or on getsize()) if B doesn't override SIZE? ``` class A: SIZE = 5 def getsize(self): return self.SIZE class B(A): pass ``` Edit: ... while inheriting the getsize() method...?

Original source