1

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.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
ROBOT AI
  • 1,217
  • 3
  • 16
  • 27
  • Note that the first sentence of the [property documentation](https://docs.python.org/2/library/functions.html#property) already answers your question: `Return a property attribute for **new-style classes** (classes that derive from **object**).` – MSeifert Jan 05 '17 at 12:52
  • @MSeifert, yes, got it. thanks! – ROBOT AI Jan 05 '17 at 13:01

1 Answers1

4

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

Alex Hall
  • 34,833
  • 5
  • 57
  • 89