Abstract attribute (not property)?

前端 未结 7 954
心在旅途
心在旅途 2020-11-30 22:41

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         


        
7条回答
  •  离开以前
    2020-11-30 23:13

    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
    

提交回复
热议问题