Python 属性()返回不同的值
我试图填补我对PythonsPython 属性()返回不同的值,python,class,properties,python-2.x,Python,Class,Properties,Python 2.x,我试图填补我对Pythonsproperty()的理解空白。 下面是我为理解property()而编写的代码: 正如您在上面看到的,当我试图通过分配t.temps=13来设置temp值时,set_temp()函数未被调用,而我希望调用该函数是因为property()功能。另外,对于变量temp 我遗漏了什么?这个问题只出现在python 2中 发件人: 类属性([fget[,fset[,fdel[,doc]])) 为新样式类(从对象派生的类)返回属性属性 (我的重点。) 如果通过继承对象使温度成
property()
的理解空白。
下面是我为理解property()
而编写的代码:
正如您在上面看到的,当我试图通过分配t.temps=13
来设置temp
值时,set_temp()
函数未被调用,而我希望调用该函数是因为property()
功能。另外,对于变量temp
我遗漏了什么?这个问题只出现在python 2中 发件人: 类属性([fget[,fset[,fdel[,doc]])) 为新样式类(从对象派生的类)返回属性属性 (我的重点。)
如果通过继承
对象
使温度
成为一个新样式的类,则该属性将按预期工作。这只是因为您使用了Python 2,而忘记了对对象
进行子类化。在您的例子中,属性
根本不起作用,因为它是一个老式类
最好将对象子类化为:
class Temperature(object):
...
或者更好:使用Python 3。Python3不再有旧式的类,您可以省略(object)
部分,因为它是隐式的
但是,如果可以使用decorator语法,则不应该定义get_temp
或set_temp
函数。你绝对不应该直接给他们打电话
这将是更具蟒蛇风格的:
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
等级温度(对象):
定义初始值(自身,温度=10):
self.temps=temp
def至_farenheit(自身):
返回(自身温度*1.8)+32
@财产
def温度(自我):
打印(“获取温度值”)
返回自我温度
@临时二传手
def温度(自身、温度):
打印(“设置温度值”)
如果温度<-237:
提升值错误(“该值应高于-273”)
其他:
自身温度=温度
该示例将在Python2和Python3上运行。使用哪一个杠杆
class Temperature(object):
...
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
class Temperature(object):
def __init__(self, temp=10):
self.temps = 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)
In [30]: t = Temperature()
setting temperature value
In [31]: t.temps
getting temperature value
Out[31]: 10
In [32]: t.temps = 100
setting temperature value
In [33]: t.temps
getting temperature value
Out[33]: 100
In [34]: t.__dict__
Out[34]: {'_temp': 100}