Abstract attribute (not property)?

前端 未结 7 972
心在旅途
心在旅途 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:16

    I've searched around for this for awhile but didn't see anything I like. As you probably know if you do:

    class AbstractFoo(object):
        @property
        def bar(self):
            raise NotImplementedError(
                    "Subclasses of AbstractFoo must set an instance attribute "
                    "self._bar in it's __init__ method")
    
    class Foo(AbstractFoo):
        def __init__(self):
            self.bar = "bar"
    
    f = Foo()
    

    You get an AttributeError: can't set attribute which is annoying.

    To get around this you can do:

    class AbstractFoo(object):
    
        @property
        def bar(self):
            try:
                return self._bar
            except AttributeError:
                raise NotImplementedError(
                    "Subclasses of AbstractFoo must set an instance attribute "
                    "self._bar in it's __init__ method")
    
    class OkFoo(AbstractFoo):
        def __init__(self):
            self._bar = 3
    
    class BadFoo(AbstractFoo):
        pass
    
    a = OkFoo()
    b = BadFoo()
    print a.bar
    print b.bar  # raises a NotImplementedError
    

    This avoids the AttributeError: can't set attribute but if you just leave off the abstract property all together:

    class AbstractFoo(object):
        pass
    
    class Foo(AbstractFoo):
        pass
    
    f = Foo()
    f.bar
    

    You get an AttributeError: 'Foo' object has no attribute 'bar' which is arguably almost as good as the NotImplementedError. So really my solution is just trading one error message from another .. and you have to use self._bar rather than self.bar in the init.

提交回复
热议问题