0

In the design of the abstract base class, I can find the following scenarios. What are the design considerations of adding @property for a method in the abstract base class. When I implement the related function, e.g., f1 here, are there any differences comparing to implementing f1, which does not have @property decorator?

@abstractmethod
def f(self)
     pass

@property
@abstractmethod
def f1(self)
    pass
user785099
  • 5,323
  • 10
  • 44
  • 62

1 Answers1

3

This would be an abstract property. From docs:

A subclass of the built-in property(), indicating an abstract property.

This special case is deprecated, as the property() decorator is now correctly identified as abstract when applied to an abstract method:

class C(ABC):
    @property
    @abstractmethod
    def my_abstract_property(self):
        ...

This would allow you to do something like this:

class CD(C):
    def my_abstract_property(self):
        return 1

cd = CD()
print(cd.my_abstract_property)
# Outputs 1

However, if you had only a @abstractmethod decorator in the first place, such as

class C(ABC):
    @abstractmethod
    def my_abstract_property(self):
        ...

you would have to do

class CD(C):
    def my_abstract_property(self):
        return 1

cd = CD()
#                            vv
print(cd.my_abstract_property())
# Outputs 1

enzo
  • 9,861
  • 3
  • 15
  • 38