某些子项中直接定义的属性,其他子项中的 属性

attribute directly defined in some childs, property in others

我有以下情况:

value = 4

class Foo(object):
    def __init__(self):
        self.d = value  # I want all childs to have this attribute

class Bar(Foo):
    def __init__(self):
        super(Bar, self).__init__()  # instances of Bar simply inherit from Foo
        self.d = 12  # and have their values set at will

class FaBoo(Foo):
    def __init__(self):
        super(FaBoo, self).__init__()  # FaBoo does as well

    @property  # but for FaBoo it is better to calculate d
    def d(self):
        return 2 * value

C = FaBoo()  # raises AttributeError

在我的例子中,可以直接为 FaBoo 定义 d,但这在某种意义上是多余的,因为我可以从 Bar 实例的 d 计算 FaBoo 实例的 d。因此,将 d 用作 FaBoo 的 属性 可减少潜在输入错误的数量。

是否可以将 FaBoo 的 d 作为 属性 而直接定义在 Foo 和 Bar 中?

编辑:用例。

这是关于双壁压力容器的。想象一下两个管子 - 圆柱形 shells (Foo) - 具有像维纳一样的半球形底部 (FaBoo);内管的半径为 r1,外管的半径为 r2。属性 d 是索引,即 1 或 2,本质上是 inner/outer shell 的 ID,需要进一步计算以识别 shell。作为输入,我只想为圆柱形部分提供此 ID,对于半球形部分,我可以通过比较 r 值找到它,例如 d = [x for x in list_of_Bars if x.r == self.r]

显然,整个情况可以通过以下方式解决:a) 比较 r 值以找出哪个是内部的,哪个是外部的,b) 为所有实例显式地给出 d 的值,但是为了进一步使用它会很多更容易显式提供一次并计算所有后续情况。

我可能会重新考虑以其他方式解决整个情况,例如在所有情况下都将 d 设置为 属性,但我认为这个问题本身很有趣。

FaBoo 将 d 定义为只读属性(因为您没有将 setter 传递给 property)并且对父初始化程序的调用尝试设置 d.

解决方案显然是通过定义无操作 setter 使 d 成为 read/write 属性 - 但这将打破大多数预期,因为可写属性应该设置时更改值....您的实际用例是什么?

编辑:如果您对基础 class 具有完全控制权,并且 d 在语义上是只读属性(或最多 "set once never update" 一个),正确的解决方案是从一开始就将其设置为只读 属性,并使用受保护的属性将值设置并存储在 FooBar.