Is there a way to declare an abstract instance variable for a class in python?
For example, we have an abstract base class, Bird
, with an abstract method fly
implemented using the abc
package, and the abstract instance variable feathers
(what I'm looking for) implemented as a property.
from abc import ABCMeta, abstractmethod
class Bird(metaclass=ABCMeta):
@property
@abstractmethod
def feathers(self):
"""The bird's feathers."""
@abstractmethod
def fly(self):
"""Take flight."""
The problem is that Eagle
, a class derived from Bird
, is required to have feathers
implemented as a property method. So the following is not an acceptable class, but I'd like it to be
class Eagle(Bird):
def __init__(self):
self.feathers = 'quill'
def fly(self):
print('boy are my arms tired')
There might be a problem since the requirement is on the instance itself, and really after its instantiation, so I don't know if things like the abc
package will still work.
Are there some standard ways of handling this?
Abstract Class Instantiation Abstract classes are not complete as they may have some methods that are not defined. So we cannot create an instance or object of an abstract class in Python. If we try to instantiate the abstract class, it raises an error.
Abstract classes can have instance variables (these are inherited by child classes). Interfaces can't. Finally, a concrete class can only extend one class (abstract or otherwise). However, a concrete class can implement many interfaces.
Abstract Class Requirements Therefore, we need to define an abstract class (not exactly) with the following requirements: the base class must not be instantiated. the base class has an abstract class variable (emphasis on class variable, which defines the schema for that model)
No. You can only declare classes as abstract, and variables as references to classes (or as value types).
The abc
system doesn't include a way to declare an abstract instance variable. The code that determines whether a class is concrete or abstract has to run before any instances exist; it can inspect a class for methods and properties easily enough, but it has no way to tell whether instances would have any particular instance attribute.
The closest thing is probably a variable annotation:
class Bird(metaclass=ABCMeta):
feathers : str
...
abc
won't do anything with that annotation, but it at least expresses to readers and static type checkers that instances of Bird
are supposed to have a feathers
instance variable. (Whether static type checkers will understand that this instance variable is supposed to come from subclasses, I don't know.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With