How to create abstract properties in python abstract classes -
in following code, create base abstract class base
. want classes inherit base
provide name
property, made property @abstractmethod
.
then created subclass of base
, called base_1
, meant supply functionality, still remain abstract. there no name
property in base_1
, nevertheless python instatinates object of class without error. how 1 create abstract properties?
from abc import abcmeta, abstractmethod class base(object): __metaclass__ = abcmeta def __init__(self, strdirconfig): self.strdirconfig = strdirconfig @abstractmethod def _dostuff(self, signals): pass @property @abstractmethod def name(self): #this property supplied inheriting classes #individually pass class base_1(base): __metaclass__ = abcmeta # class not provide name property, should raise error def __init__(self, strdirconfig): super(base_1, self).__init__(strdirconfig) def _dostuff(self, signals): print 'base_1 stuff' class c(base_1): @property def name(self): return 'class c' if __name__ == '__main__': b1 = base_1('abc')
until python 3.3, cannot nest @abstractmethod
, @property
.
use @abstractproperty
create abstract properties (docs).
from abc import abcmeta, abstractmethod, abstractproperty class base(object): # ... @abstractproperty def name(self): pass
the code raises correct exception:
traceback (most recent call last): file "foo.py", line 36, in b1 = base_1('abc') typeerror: can't instantiate abstract class base_1 abstract methods name
Comments
Post a Comment