Say I have the following code:
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
so know what is the best pythonic way to override the setter and getter method of the Abstract class attribute mode.
Overriding @mode.setter in the sub-class GzipGPGArchive causes unresolved reference!
Simon Gibbons
7,2241 gold badge25 silver badges35 bronze badges
asked Nov 3, 2015 at 10:20
arash javanmard
1,3872 gold badges18 silver badges38 bronze badges
1 Answer 1
First of all, there is no such thing as abstract attributes in Python. You can achieve abstraction, however, by using abc module. Perhaps it is not really "pythonic", but it works.
This is the minimal example with inheritance and abstraction. Use it as as template:
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
answered Nov 3, 2015 at 10:37
Andrejs Cainikovs
28.7k2 gold badges81 silver badges99 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
arash javanmard
this worked for me, BUT what is really the right pythonic to doing such a things???
lang-py
self._modein the initializer (__init__), otherwise after creating an instance you try to read the property (before setting it) you'll get anAttributeError.