相关疑难解决方法(0)

覆盖继承的属性setter

我有一类叫做Node一个具有importancesetter和getter,如下:

class Node:

    @property
    def importance(self):
        return self._importance

    @importance.setter
    def importance(self, new_importance):
        if new_importance is not None:
            new_importance = check_type_and_clean(new_importance, int)
            assert new_importance >= 1 and new_importance <= 10
        self._importance = new_importance
Run Code Online (Sandbox Code Playgroud)

后来,我有一个Theorem继承自的类Node.就所涉及的而言,a Theorem和a 之间的唯一区别是必须具有至少一个.NodeimportanceTheoremimportance3

一个定理如何能继承importance二传手,但增加的附加约束importance >= 3

我试着这样做:

class Theorem(Node):

    @importance.setter
    def importance(self, new_importance):
        self.importance = new_importance # hoping this would use the super() setter
        assert self.importance >= 3
Run Code Online (Sandbox Code Playgroud)

python oop inheritance python-3.x

11
推荐指数
2
解决办法
4518
查看次数

标签 统计

inheritance ×1

oop ×1

python ×1

python-3.x ×1