Since Python 3.3 a bug was fixed meaning the property() decorator is now correctly identified as abstract when applied to an abstract method.
Note: Order matters, you have to use @property above @abstractmethod
Python 3.3+: (python docs):
from abc import ABC, abstractmethod
class C(ABC):
@property
@abstractmethod
def my_abstract_property(self):
...
Python 2: (python docs)
from abc import ABCMeta, abstractproperty
class C:
__metaclass__ = ABCMeta
@abstractproperty
def my_abstract_property(self):
...
Answer from James on Stack OverflowSince Python 3.3 a bug was fixed meaning the property() decorator is now correctly identified as abstract when applied to an abstract method.
Note: Order matters, you have to use @property above @abstractmethod
Python 3.3+: (python docs):
from abc import ABC, abstractmethod
class C(ABC):
@property
@abstractmethod
def my_abstract_property(self):
...
Python 2: (python docs)
from abc import ABCMeta, abstractproperty
class C:
__metaclass__ = ABCMeta
@abstractproperty
def my_abstract_property(self):
...
Until Python 3.3, you cannot nest @abstractmethod and @property.
Use @abstractproperty to create abstract properties (docs).
from abc import ABCMeta, abstractmethod, abstractproperty
class Base(object):
# ...
@abstractproperty
def name(self):
pass
The code now raises the correct exception:
Traceback (most recent call last):
File "foo.py", line 36, in
b1 = Base_1('abc')
TypeError: Can't instantiate abstract class Base_1 with abstract methods name
Is there a such thing as declaring an attribute of an abstract class in Python?
How to define an abstract property?
Abstract properties in Python's abstract base classes: good practices
[abc] Add abstract attributes via `abstract` type-hint - Ideas - Discussions on Python.org
Can an abstract class have properties in Python?
What is an abstract class in Python?
What is the purpose of abstract methods in Python?
Videos
I come from a C++ background, and I need to write an abstract base class, that inherits from abc. In this abstract base class, I would like to "declare" (this is C++ lingo, but I don't think variable declaration is a thing in Python) an uninstantiated variable, say `var`, which is initialized in the subclasses.
I'm wondering if there's any way to do this in Python?