Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 @Property.setter and Object has no attribute

I am learning about objects with Python with "the Quick Python Book" second edition. I am using Python 3

I am trying to learn about the @property along with the setters for the property. From page 199 chpt 15 it has this example that I tried but I get errors:

>>> 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 am I getting this error? Also, why couldn't I just set the instance variable new_temp with a function call and parameter like:

t = Temparature()
t.temp(34)

instead of

t.temp = 43
like image 442
dman Avatar asked Jan 17 '26 05:01

dman


1 Answers

You've defined all of your methods inside the __init__ method! Just unindent them like so:

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)

doesn't work because properties are descriptors and they have lookup precedence in this case so t.temp returns the @property that you defined.

like image 164
jamylak Avatar answered Jan 19 '26 19:01

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!