覆盖继承的属性设置器 [英] Overriding an inherited property setter

查看:44
本文介绍了覆盖继承的属性设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做Node的类,下面有一个importance setter和getter:

I have a class called Node that has an importance setter and getter, below:

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

稍后,我有一个从Node继承的类Theorem.就importance而言,TheoremNode之间的唯一区别是Theoremimportance必须至少为3.

Later on, I have a class Theorem that inherits from Node. The only difference between a Theorem and a Node, as far as importance is concerned, is that a Theorem must have an importance of at least 3.

定理如何继承 importance设置器,但要添加importance >= 3的附加约束?

How can a Theorem inherit the importance setter, but add on the additional constraint that 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

推荐答案

您可以直接通过Node类引用现有属性,并使用该属性的setter方法从中创建一个新属性:

You can refer to the existing property directly through the Node class, and use the property's setter method to create a new property from it:

class Theorem(Node):
    @Node.importance.setter
    def importance(self, new_importance):
        # You can change the order of these two lines:
        assert new_importance >= 3
        Node.importance.fset(self, new_importance)

这将在Theorem类中创建一个新属性,该属性使用Node.importance中的getter方法,但将setter方法替换为其他属性. 属性通常就是这样工作的:调用属性的setter会返回带有自定义设置器的新属性,该设置器通常仅替换旧属性.

This will create a new property into Theorem class that uses the getter method from Node.importance but replaces the setter method with a different one. That's how properties in general work: calling a property's setter returns a new property with a custom setter, which usually just replaces the old property.

您可以通过阅读此答案(还有问题)来了解有关属性工作原理的更多信息.

You can learn more about how properties work by reading this answer (and the question too).

这篇关于覆盖继承的属性设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆