首页 > 其他 > 详细

045魔法方法:属性访问

时间:2015-10-21 08:06:22      阅读:274      评论:0      收藏:0      [点我收藏+]

属性访问:
__getattr__(self,name)
  定义当用户试图获取一个不存在的属性时的行为

__getattribute__(self,name)
  定义当该类的属性被访问时的行为

__setattr__(self,name,value)
  定义当用一个属性被设置时的行为

__delattr__(self,name)
  定义当用一个属性被删除时的行为


例:>>> class C:
  ...     def __getattribute__(self, name):
          # 使用 super() 调用 object 基类的 __getattribute__ 方法
  ...         print(‘getattribute‘)
  ...         return super().__getattribute__(name)
  ...     
  ...     def __setattr__(self, name, value):
  ...         print(‘setattr‘)
  ...         super().__setattr__(name, value)
  ...     def __delattr__(self, name):
  ...         print(‘delattr‘)
  ...         super().__delattr__(name)
  ...     def __getattr__(self, name):
  ...         print(‘getattr‘)
  ...
  >>> c = C()
  >>> c.x
  getattribute
  getattr
  >>> c.x = 1
  setattr
  >>> c.x
  getattribute
  1
  >>>del c.x
  delattr


练习:
写一个矩形类,默认有宽和高两个属性;
如果为一个叫square的属性赋值,那么说明这是一个正方形,值就是正方形的边长,此时宽和高都应该等于边长。
class Rectangle:
    def __init__(self, width=0, height=0):
        self.width = width
        self.height = height
 
    def __setattr__(self, name, value):
        if name == ‘square‘:
            self.width = value
            self.height = value
        else:
            self.__dict__[name] = value   #注意,避免进入死循环
 
    def getArea(self):
        return self.width * self.height


045魔法方法:属性访问

原文:http://www.cnblogs.com/wangjiaxing/p/4896672.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!