Python进阶之“property(属性)”详解

一、@property 简单实例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

class Rectangle(object):

  @property

  def width(self):

    #变量名不与方法名重复,改为true_width,下同

    return self.true_width

 

  @property

  def height(self):

    return self.true_height

s = Rectangle()

#与方法名一致

s.width = 1024

s.height = 768

print(s.width,s.height)

二、保存温度实例

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值