Python3 @Property.setter and Object have no properties … here is a solution to the problem.
Python3 @Property.setter and Object have no properties
I’m learning objects using Python with the second edition of “The Quick Python Book”. I’m using Python 3
I’m trying to understand the @property and the setter for that property.
From page 199, chapter 15, I tried this example and got an error :
>>> class Temparature:
def __init__(self):
self._temp_fahr = 0
@property
def temp(self):
return (self._temp_fahr - 32) * 5/9
@temp.setter
def temp(self, new_temp):
self._temp_fahr = new_temp * 9 / 5 + 32
>>> t.temp
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
t.temp
AttributeError: 'Temparature' object has no attribute 'temp'
>>>
Why does this error occur? Also, why can’t I just set the instance variable new_temp with function calls and parameters, for example:
t = Temparature()
t.temp(34)
Replace
t.temp = 43
Solution
You have defined all the methods in the __init__
method! Cancel indentation like this:
class Temparature:
def __init__(self):
self._temp_fahr = 0
@property
def temp(self):
return (self._temp_fahr - 32) * 5/9
@temp.setter
def temp(self, new_temp):
self._temp_fahr = new_temp * 9 / 5 + 32
This
t.temp(34)
Does not work because the attributes are descriptors in this case they have a lookup priority, so t.temp
returns what you defined @property
。