Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

inheritance - 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)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...