What\'s the best practice to define an abstract instance attribute, but not as a property?
I would like to write something like:
class AbstractFoo(me
If you really want to enforce that a subclass define a given attribute, you can use metaclass. Personally, I think it may be overkill and not very pythonic, but you could do something like this:
class AbstractFooMeta(type):
def __call__(cls, *args, **kwargs):
"""Called when you call Foo(*args, **kwargs) """
obj = type.__call__(cls, *args, **kwargs)
obj.check_bar()
return obj
class AbstractFoo(object):
__metaclass__ = AbstractFooMeta
bar = None
def check_bar(self):
if self.bar is None:
raise NotImplementedError('Subclasses must define bar')
class GoodFoo(AbstractFoo):
def __init__(self):
self.bar = 3
class BadFoo(AbstractFoo):
def __init__(self):
pass
Basically the meta class redefine __call__
to make sure check_bar
is called after the init on an instance.
GoodFoo() # ok
BadFoo () # yield NotImplementedError