說我有下面的代碼:Python的抽象屬性和繼承
class Archive(object):
""" Archiv-File wrapper """
READ_MODE = 0
WRITE_MODE = 1
def __init__(self, file_):
self.file_ = file_
self._mode = None
@property
def mode(self):
return self._mode
@mode.setter
def mode(self, value):
self._mode = value
def open(self, mode="r", pwd=None):
raise NotImplemented("Subclasses should implement this method!")
def close(self):
raise NotImplemented("Subclasses should implement this method!")
################################################
class GzipGPGArchive(Archive):
READ_MODE = 'r:gz' # Open for reading with gzip compression.
WRITE_MODE = 'w:gz' # Open for gzip compressed writing.
SUFFIX = "tar.gz.gpg"
def __init__(self, *args, **kwargs):
super(GzipGPGArchive, self).__init__(*args, **kwargs)
@mode.setter # This causes unresolved reference
def mode(self, value):
# do internal changes
self._mode = value
def open(self):
pass
def close(self):
pass
所以知道什麼是重寫抽象類屬性mode
的setter和getter方法最好的Python的方式。
覆蓋@mode.setter
中的子類GzipGPGArchive
導致未解決的參考!
您可能要初始化'self._mode'在初始化('__init__'),創建一個實例後,否則你嘗試讀取屬性(設置它之前),你會得到一個'AttributeError'。 – CristiFati
@CristiFati糾正了它,謝謝 –