一、@property 简单实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
二、保存温度实例
property 它使得面向对象的编程更加简单。在详细解释和深入了解Python中的property之前,让我们先了解为什么我们需要用到property?
假设有天你决定创建一个类,用来存储摄氏温度。当然这个类也需要实现一个将摄氏温度转换为华氏温度的方法。一种实现的方式如下:
1 2 3 4 5 |
class Celsius: def __init__(self, temperature = 0): self.temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32 |
我们可以用这个类产生一个对象,然后按照我们期望的方式改变该对象的温度属性:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
>>> # create new object >>> man = Celsius()
>>> # set temperature >>> man.temperature = 37
>>> # get temperature >>> man.temperature 37
>>> # get degrees Fahrenheit >>> man.to_fahrenheit() 98.60000000000001 | <