Trong đoạn mã sau, tôi tạo một lớp trừu tượng cơ sở Base
. Tôi muốn tất cả các lớp kế thừa từ đó Base
cung cấp thuộc name
tính, vì vậy tôi đã tạo thuộc tính này là an @abstractmethod
.
Sau đó, tôi tạo một lớp con Base
, được gọi là Base_1
, có nghĩa là cung cấp một số chức năng, nhưng vẫn còn trừu tượng. Không có name
thuộc tính trong Base_1
, nhưng tuy nhiên, python cài đặt một đối tượng của lớp đó mà không có lỗi. Làm thế nào để tạo ra các thuộc tính trừu tượng?
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 will be supplied by the inheriting classes
#individually
pass
class Base_1(Base):
__metaclass__ = ABCMeta
# this class does not provide the name property, should raise an error
def __init__(self, strDirConfig):
super(Base_1, self).__init__(strDirConfig)
def _doStuff(self, signals):
print 'Base_1 does stuff'
class C(Base_1):
@property
def name(self):
return 'class C'
if __name__ == '__main__':
b1 = Base_1('abc')
@property
trongclass C
,name
sẽ hoàn nguyên về một phương thức.