pythoninheritancepropertiessubclassabstract-methods

force subclass to implement property python


Tried the answer from force-implementing-specific-attributes-in-subclass

But does not work. This code still passes with no errors.

#python version: 3.8.1
from abc import ABC, abstractmethod

class A(ABC):
    @property
    @abstractmethod
    def pr(self):
        return 0
    
class B(A):
    def pr(self):# not a property.
        return 5
    
b = B()

print(b.pr())

So how can I force subclasses to implement specific properties(pr as above)?


Solution

  • The code passes with no errors because you have given a concrete implementation for the abstract method, in the subclass, and it looks (not sure) that it is the only thing abc cares about. Also if you override, there is no way to have the same decorators from the parent class applied automatically, you have to repeat the property decorator syntax.

    The best threads I found about that are this and this. Please read them fully.

    Besides, there is a recent Python bug, that looks closed without solving (or is it re-opened?). Read the full thread there too. Interesting and related.