【问题标题】:Need help on python Descriptor functionality需要有关 python 描述符功能的帮助
【发布时间】:2019-02-20 20:51:11
【问题描述】:

我正在尝试使用 python 描述符解决问题。 代码如下

class Celsius( object ):
    def __init__( self, value=0.0 ):
        self.value= float(value)
    def __get__( self, instance, owner ):
        return float(self.value)
    def __set__( self, instance, value ):
        self.value= float(value)

class Fahrenheit( object ):
    def __get__( self, instance, owner ):
        return (instance.celsius * 9 / 5 + 32.0)
    def __set__( self, instance, value ):
        instance.celsius= (float(value)-32.0) * 5 / 9

class Temperature( object ):
    def __init__(self, fahrenheit):
        self.fahrenheit = fahrenheit

    fahrenheit = Fahrenheit()
    celsius = Celsius()

t1 = Temperature(32)
print(t1.fahrenheit, t1.celsius)
t1.celsius = 0
print(t1.fahrenheit, t1.celsius)

预期的 O/P 是

32 0.0
32.0 0.0

但我明白了

32.0 0.0
32.0 0.0

请帮助我应该在哪里更改或是否有其他更好的方法。

【问题讨论】:

  • 他们都返回floats,你为什么要在那里期待int
  • 你说你得到的输出是我对你的代码的期望。为什么你认为你第一次访问它时应该从t1.fahrenheit 获得32?此外,该描述符设计非常奇怪,因为Temperature 的每个实例都将共享相同的温度值(因为它们位于Celsius 描述符实例中)。将基础值保存在某个地方的实例中会更自然。
  • 我需要将 O/P 设为 32 0.0 32.0 0.0 。我正在尝试弄清楚如何做到这一点
  • 我正在寻找在我的代码中进行哪些更改以获得所需的 O/P

标签: python python-descriptors


【解决方案1】:

没有解释为什么你想要你想要的输出......只是你想要那个输出,你可以通过将代码的最后四行更改为:

t1 = Temperature(32)
print(int(t1.fahrenheit), t1.celsius)
t1.celsius = 0
print(t1.fahrenheit, t1.celsius)

输出:

32 0.0
32.0 0.0

我假设你想要的不是这个,但我不知道你可能想要什么。您从代码中获得的输出是完全合理的。

【讨论】:

    【解决方案2】:

    摄氏度: def get(self, instance, owner): 返回 5 * (instance.fahrenheit - 32) /9

    def __set__(self, instance, value):
        instance.fahrenheit = 32 + 9 * value/5
    

    类温度: 摄氏度 = 摄氏度()

    def __init__(self, initial_f):
        self.fahrenheit = initial_f
    

    【讨论】:

      【解决方案3】:

      问题是当你给fahrenheit赋值时,Fahrenheit__set__()方法委托给instance.celsiusCelsius 上的所有方法都转换为 float。如果您希望您的示例按预期工作,则需要Celsius 委托给instance.fahrenheit,同时仍然进行float 转换,如果这是您想要的,可能仅在__get__() 中进行。

      所以,总而言之,存储在Fahrenheit 类型中而不进行类型转换,并从Celsius 委托给Fahrenheit

      正如其他人所指出的,您的描述符设计使得Temperature 的所有实例都将存储相同的值。如果您希望不同的实例保存不同的值,则需要将值直接保存在实例上以不同的名称(通常,在这种情况下为_fahrenheit),或者保存在密钥所在的一种字典中instance.

      最后,对于这种在两个描述符之间共享一个值并且它们不太可能在其他地方重用的情况,我会走property 路线。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多