The Property Function

First, consider the following Rectangle class:

class Rectangle:
      def __init__(self):
          self.width = 0
          self.height = 0
      def setSize(self, size):
          self.width, self.height = size
      def getSize(self):
          return self.width, self.height
>>> r = Rectangle()
>>> r.width = 10
>>> r.height = 5
>>> r.getSize()
(10, 5)
>>> r.setSize((150, 100))
>>> r.width
150
This code isn't directly wrong, but it is flawed. The programmer using this class shouldn't need to worry about how it is implemented.(encapsulation). It would be impractical (and kind of silly) if you had a lot of simple attributes, because you would need to write many accessors that did nothing but retrieve or set these attributes, with no useful action taken.  Luckily, Python can hide your accessors for you, making all of your  attributes look alike. Those attributes that are defined through their accessors are often called properties.

__metaclass__ = type
class Rectangle:
      def __init__(self):
          self.width = 0
          self.height = 0
      def setSize(self, size):
          self.width, self.height = size
      def getSize(self):
          return self.width, self.height
      size = property(getSize, setSize)
After this, you no longer need to worry about how things are implemented, but can treat width, height, and size the same way:
>>> r = Rectangle()
>>> r.width = 10
>>> r.height = 5
>>> r.size
(10, 5)
>>> r.size = 150, 100
>>> r.width
150
As you can see, the size attribute is still subject to the calculations in getSize and setSize,but it looks just like a normal attribute. T hat is to say, property function make "attribute" the interface of class. The moral is this: with new-style classes, you should use property rather than accessors. Considering more about property,it isn't really a function—it's a class whose instances have some magic methods that do all the work.  The methods in question are __get__, __set__, and __delete__. Together, these three methods define the so-called descriptor protocol.  In fact, the mechanism underlying properties, bound methods, static and class methods, and super.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值