Reputation: 57421
I'm trying to follow a tutorial on http://www.programiz.com/python-programming/property, and have written the following script:
class Celsius:
def __init__(self, temperature = 0):
self.temperature = temperature
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()
print c.temperature
c.temperature = 100
print c.temperature
When I run the script, I simply see the two temperature values:
0
100
However, I would expect the Getting value
and Setting value
print statements to be visible as well. Is the property
somehow not working properly?
Upvotes: 1
Views: 102
Reputation: 657
you need define class as this:
class Celsius(object):
balabala
balabala
Upvotes: 1
Reputation: 78546
The code should work as is, but you're mixing Python 2 syntax with Python 3.
If you turn the print
statements outside the class into function calls, the code works fine as valid Python 3.
If you'll run this as Python 2 code, then you have to inherit your class from object
and keep every other thing as is.
Choose one.
Upvotes: 1
Reputation: 59093
What you're trying to do only works in new-style classes. To declare a new-style class in Python 2, you need to have
class Celsius(object):
instead of
class Celsius:
In Python 3, all classes are new-style, so the plain class Celsius
works fine.
Upvotes: 2