为超类中定义的属性定义@ property.setter

时间:2016-07-15 17:31:19

标签: python inheritance

我有一组表示音轨的类和元数据。对于某些文件格式,我只支持读取标记,对于其他文件格式也是如此。

class ReadableTrack(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def _get_artist(self):
        raise NotImplementedError

    @property
    def artist(self):
        return self._get_artist()


class DsfTrack(ReadableTrack):
    """
        Support for DSF files
    """
    def _get__get_artist(self):
        pass  # code here

支持写入元的文件格式是从ReadableTrack的子类派生的,它实现了标记的setter

class WritableTrack(ReadableTrack):
    """
        A track to which metadata can also be written.
    """

    @abc.abstractmethod
    def _set_artist(self, artist):
        raise NotImplementedError

    @artist.setter
    def artist(self, value):
        self._set_artist()


class FlacTrack(WritableTrack):
    """
        Class to get the metadata from .flac file extensions
    """

    def _get_artist(self):
        pass  # code here

    def _set_artist(self, value):
        pass  # code here

不幸的是,上述情况会导致以下错误:

File "/system/audio/metadata/Track/FlacTrack.py", line 11, in <module>
    from system.audio.metadata.Track import WritableTrack
  File "/system/audio/metadata/Track/__init__.py", line 23, in <module>
    from system.audio.metadata.Track.WritableTrack import WritableTrack
  File "/system/audio/metadata/Track/WritableTrack.py", line 13, in <module>
    class WritableTrack(ReadableTrack):
  File "/system/audio/metadata/Track/WritableTrack.py", line 171, in WritableTrack
    @artist.setter
NameError: name 'artist' is not defined

可以&#34;解决方法&#34;通过重新定义WritableTrack中的艺术家属性,如此:

class WritableTrack2(ReadableTrack):
    """
        A track to which metadata can also be written.
    """

    @abc.abstractmethod
    def _get_artist(self):
        raise NotImplementedError

    @abc.abstractmethod
    def _set_artist(self, value):
        raise NotImplementedError

    @property
    def artist(self):
        return self._get_artist()

    @artist.setter
    def artist(self, value):
        self._set_artist(value)

所以基本上在WritableTrack中,我不能为超类中定义的属性定义@ property.setter。这些属性在超类中定义,因为它们包含一些I / O验证,以确保ReadableTrack和WritableTrack的各个子类之间的接口一致性。重新定义属性是多余的,并且违背了继承的目的......我想找到&#34;正确的&#34;这样做的方式。任何提示?

0 个答案:

没有答案