property()返回不同的值

coo*_*l77 3 python properties class python-2.x

我试图填补我对蟒蛇的理解中的空白property().以下是我提出的代码,以了解property():

class Temperature:
    def __init__(self, temp = 10):
        self.set_temp(temp)

    def to_farenheit(self):
        return (self._temp * 1.8) + 32

    def get_temp(self):
        print "getting temperature value"
        return self._temp

    def set_temp(self, temp):
        print "setting temperature value"

        if temp < -237:
            raise ValueError("this shud be above -273")
        else:
            self._temp = temp

    temps = property(get_temp, set_temp)
Run Code Online (Sandbox Code Playgroud)

我执行上面的类并执行以下操作:

>>> t = Temperature()
setting temperature value

>>> t.temps
getting temperature value
10

>>> t.temps = 13

>>> t.temps
13
>>> t.get_temp()
getting temperature value
10
>>> 
Run Code Online (Sandbox Code Playgroud)

正如您在上面所看到的,当我尝试temp通过分配函数来设置值时,t.temps = 13由于set_temp()功能的原因,我不希望调用该property()函数.另外,我最终得到了两个不同的变量值temp

我错过了什么?

MSe*_*ert 8

这只是因为你使用Python 2而忘记了子类object.在你的情况下property根本不起作用,因为它是一个旧式的类.

更好的子类object:

class Temperature(object):
    ...
Run Code Online (Sandbox Code Playgroud)

甚至更好:使用Python 3. Python 3不再具有旧式类,您可以省略该(object)部分,因为它是隐式的.

但是,当您可以使用装饰器语法时,您真的不应该定义get_tempset_temp运行.你绝对不应该直接打电话给他们.

这将更加pythonic:

class Temperature(object):
    def __init__(self, temp = 10):
        self.temps = temp

    def to_farenheit(self):
        return (self._temp * 1.8) + 32

    @property
    def temps(self):
        print("getting temperature value")
        return self._temp

    @temps.setter
    def temps(self, temp):
        print("setting temperature value")
        if temp < -237:
            raise ValueError("this shud be above -273")
        else:
            self._temp = temp
Run Code Online (Sandbox Code Playgroud)

该示例适用于Python 2 Python 3.