2015-11-03 122 views
0

說我有下面的代碼: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導致未解決的參考!

+0

您可能要初始化'self._mode'在初始化('__init__'),創建一個實例後,否則你嘗試讀取屬性(設置它之前),你會得到一個'AttributeError'。 – CristiFati

+0

@CristiFati糾正了它,謝謝 –

回答

3

首先,Python中不存在抽象屬性。但是,您可以通過使用abc模塊來實現抽象。也許它不是真的「pythonic」,但它的工作原理。

這是繼承和抽象的最小例子。使用它作爲模板:

from abc import ABCMeta, abstractmethod 

class Mother(metaclass=ABCMeta): 

    @abstractmethod 
    def method_(self): 
     pass 

    @property 
    @abstractmethod 
    def property_(self): 
     return -1 

    @property_.setter 
    @abstractmethod 
    def property_(self, value): 
     pass 

class Daughter(Mother): 

    def __init__(self): 
     self.value_ = 0 

    def method_(self): 
     print(self.value_) 

    @property 
    def property_(self): 
     return = self.value_ 

    @property_.setter 
    def property_(self, value): 
     self.value_ = value 
+0

這對我有用,但真正做到這樣的事情是正確的pythonic? –

+0

沒有抽象:) –