What I'd really like to do is something like this:
class X(metaclass=abc.ABCMeta):
@abc.abstractAttribute # this doesn't exist
var = [1,2]
class Y(X):
var = X.var + [3,4]
This would force any subclasses of X
to implement a static var
attribute.
But there's no way to define a static attribute as abstract.
Attempting to use @abc.abstractmethod, combined with property, I can get close:
class X(metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def var(self):
return [1,2]
class Y(X):
@property
def var(self):
return super().var + [3,4]
y=Y(); y.var
gives [1,2,3,4]
as desired.
But the goal is to create a static attribute/property, not an instance attribute/property.
When creating as a @staticmethod:
class X(metaclass=abc.ABCMeta):
@property
@staticmethod
@abc.abstractmethod
def var():
return [1,2]
class Y(X):
@property
@staticmethod
def var():
return X.var + [3,4]
... then y=Y(); y.var
gives TypeError 'staticmethod' object is not callable
If I switch the decorator order, this will resolve the staticmethod callable error:
class X(metaclass=abc.ABCMeta):
@staticmethod
@property
@abc.abstractmethod
def var():
return [1,2]
class Y(X):
@staticmethod
@property
def var():
return X.var + [3,4]
The static method will work, but the property will not function as intended: y=Y(); y.var
returns the property itself, <property at 0x2c16aa1b3b8>
.
This answer is close to what's desired, but it doesn't work in this case since the base class, X
, will already have a var
attribute (so subclass can access via super).
How do you define a python class to have an abstract, static attribute/property?