Question: About property class in a python

Question

About property class in a python

Answers 2
Added at 2017-01-05 13:01
Tags
Question

I saw a python snippet as below when seeking for a tutorial to property in python:

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    def get_temperature(self):
        print("Getting value")
        return self._temperature

    def set_temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value

    temperature = property(get_temperature,set_temperature)

c = Celsius()

The author said running this snippet would get the following output

Setting value

, because during the construction phase of the Celsius's instance (c), the setter of class member temperature is invoked, i.e. set_temperature(). This explanation makes sense, however in my own computer, I get nothing as output after running this snippet. Is anything wrong here? My python version is 2.7.6 within Ubuntu 14.04.

Answers to

About property class in a python

nr: #1 dodano: 2017-01-05 13:01

In Python 2, class Celsius: declares an old-style class, for which properties don't work. Use class Celsius(object):.

nr: #2 dodano: 2017-01-05 13:01

Isn't mandatory to use Celcius(object). The issue is that you are not passing the value to the constructer.

Try this...

c = Celsius(24) print(c.get_temperature())

Source Show
◀ Wstecz