《零基础入门学习Python》第045讲:魔法方法:属性访问

0. 请写下这一节课你学习到的内容:格式不限,回忆并复述是加强记忆的好方式!

我们这节课说说魔法方法关于属性访问的应用。我们知道可以使用点操作符(.)的形式去访问对象属性。我们在类与对象相关的BIF这一节中,我们可以使用几个BIF有礼貌的去访问属性,例如:

 
  1. >>> class C:

  2. def __init__(self):

  3. self.x = 'x-man'

  4. >>> c = C()

  5. >>> c.x

  6. 'x-man'

  7. >>> getattr(c, 'x', '没有这个属性')

  8. 'x-man'

  9. >>> getattr(c, 'y', '没有这个属性')

  10. '没有这个属性'

另外,我们还介绍过setattrdelattr 分别是设置属性和删除属性,忘了的话可以回头看一下笔记。然后还介绍了property函数的用法,property使得我们以属性的方法去访问属性。例如:

 
  1. >>> class C:

  2. def __init__(self, size = 10):

  3. self.size = size

  4. def getSize(self):

  5. return self.size

  6. def setSize(self, value):

  7. self.size = value

  8. def delSize(self):

  9. del self.size

  10. x = property(getSize, setSize, delSize)

  11. >>> c = C()

  12. >>> c.x

  13. 10

  14. >>> c.x = 1

  15. >>> c.size

  16. 1

  17. >>> del c.x

  18. >>> c.size

  19. Traceback (most recent call last):

  20. File "<pyshell#24>", line 1, in <module>

  21. c.size

  22. AttributeError: 'C' object has no attribute 'size'

关于属性访问也有相应的魔法方法来管理,通过这些魔法方法的重写可以随心所欲的控制对象的属性访问。下面是今天要讲解的四个魔法方法:

(一)__getattr__(self, name)

–定义当用户试图获取一个不存在的属性时的行为

(二)__getattribute__(self, name)

–定义当该类的属性被访问时的行为

(三)__setattr__(self, name, value)

–定义当一个属性被设置时的行为

(四)__delattr__(self, name)

–定义当一个属性被删除时的行为

也就是说,我们只要重写以上四个魔法方法,就可以空置对象的属性访问了,我们举例说明来测试一下这四个魔法方法的前后关系、因果关系:

 
  1. >>> class C:

  2. def __getattr__(self, name):

  3. print("getattr")

  4. def __getattribute__(self, name):

  5. print("getattribute")

  6. return super().__getattribute__(name)

  7. def __setattr__(self, name, value):

  8. print("setatrtr")

  9. super().__setattr__(name, value)

  10. def __delattr__(self, name):

  11. print("delattr")

  12. super().__delattr__(name)

  13. >>> c = C()

  14. >>> c.x

  15. getattribute

  16. getattr

  17. >>> c.x = 1

  18. setatrtr

  19. >>> c.x

  20. getattribute

  21. 1

  22. >>> del c.x

  23. delattr

  24. >>> c.x

  25. getattribute

  26. getattr

我们通过 print() 来在调用该魔法方法的时候打印一下,这是最好的调试方式。第一次c.x 的时候,对象是没有任何属性的,此时会先访问 getattribute,当属性不存在时,再去访问 getattr,设置属性时访问 setattr,删除属性时访问 delattr。

这几个魔法方法在使用时,需要注意 死循环 陷阱。举例说明:我们试着写下面这个程序:

•写一个矩形类,默认有宽和高两个属性;

•如果为一个叫square的属性赋值,那么说明这是一个正方形,值就是正方形的边长,此时宽和高都应该等于边长。

 
  1. class Rectangle:

  2. def __init__(self, width = 0, height = 0):

  3. self.width = width

  4. self.height = height

  5. def __setattr__(self, name, value):

  6. if name = 'square':

  7. self.width = value

  8. self.height = value

  9. else:

  10. self.name = value

  11. def getArea(self):

  12. return self.width * self.height

  13. ============ RESTART: C:/Users/XiangyangDai/Desktop/上课代码/45-1.py ============

  14. >>> r = Rectangle(4, 5)

  15. Traceback (most recent call last):

  16. File "<pyshell#50>", line 1, in <module>

  17. r = Rectangle(4, 5)

  18. File "C:/Users/XiangyangDai/Desktop/上课代码/45-1.py", line 3, in __init__

  19. self.width = width

  20. File "C:/Users/XiangyangDai/Desktop/上课代码/45-1.py", line 10, in __setattr__

  21. self.name = value

  22. File "C:/Users/XiangyangDai/Desktop/上课代码/45-1.py", line 10, in __setattr__

  23. self.name = value

  24. ..........

当我们运行并初始化时,就会进入死循环,这是为什么呢?这是因为初始化时,就会调用 __setattr__魔法方法,然后就会执行 self.name = value,而这个又会调用 __setattr__魔法方法,然后就进入死循环了,解决方法是什么呢?

就是把 self.name = value 这条语句改为调用基类的  __setattr__魔法方法(未被改写的魔法方法)。如下:

 
  1. class Rectangle:

  2. def __init__(self, width = 0, height = 0):

  3. self.width = width

  4. self.height = height

  5. def __setattr__(self, name, value):

  6. if name == 'square':

  7. self.width = value

  8. self.height = value

  9. else:

  10. super().__setattr__(name, value)

  11. def getArea(self):

  12. return self.width * self.height

 
  1. >>> r = Rectangle(4, 5)

  2. >>> r.height

  3. 5

  4. >>> r.width

  5. 4

  6. >>> r.getArea()

  7. 20

  8. >>> r.square = 10

  9. >>> r.width

  10. 10

  11. >>> r.height

  12. 10

  13. >>> r.getArea()

  14. 100

除了 __setattr__魔法方法,__getattribute__魔法方法也会陷入死循环的陷阱,如果一直去获得,就会重复的获得,死循环。推荐的解决方法就是使用基类的方法去设置、去获得。


测试题

0. 请问以下代码的作用是什么?这样写正确吗?(如果不正确,请改正)

 
  1. def __setattr__(self, name, value):

  2. self.name = value + 1

答:这段代码试图在对象的属性发生赋值操作的时候,将实际的值 +1赋值给相应的属性。但这么写法是错误的,因为每当属性被赋值的时候, __setattr__() 会被调用,而里边的 self.name = value + 1 语句又会再次触发 __setattr__() 调用,导致无限递归。

代码应该这样写:

 
  1. def __setattr__(self, name, value):

  2. self.__dict__[name] = value + 1

或者:

 
  1. def __setattr__(self, name, value):

  2. super().__setattr__(name, value+1)

1. 自定义该类的属性被访问的行为,你应该重写哪个魔法方法?

答:__getattribute__(self, name)

2. 在不上机验证的情况下,你能推断以下代码分别会显示什么吗?

 
  1. >>> class C:

  2. def __getattr__(self, name):

  3. print(1)

  4. def __getattribute__(self, name):

  5. print(2)

  6. def __setattr__(self, name, value):

  7. print(3)

  8. def __delattr__(self, name):

  9. print(4)

  10. >>> c = C()

  11. >>> c.x = 1

  12. # 位置一,请问这里会显示什么?

  13. >>> print(c.x)

  14. # 位置二,请问这里会显示什么?

答:位置一会显示 3,因为 c.x = 1 是赋值操作,所以会访问 __setattr__() 魔法方法;位置二会显示 2 和 None,因为 x 是属于实例对象 c 的属性,所以 c.x 是访问一个存在的属性,因此会访问 __getattribute__() 魔法方法,但我们重写了这个方法,使得它不能按照正常的逻辑返回属性值,而是打印一个 2 代替,由于我们没有写返回值,所以紧接着返回 None 并被 print() 打印出来。

3. 在不上机验证的情况下,你能推断以下代码分别会显示什么吗?

 
  1. >>> class C:

  2. def __getattr__(self, name):

  3. print(1)

  4. return super().__getattr__(name)

  5. def __getattribute__(self, name):

  6. print(2)

  7. return super().__getattribute__(name)

  8. def __setattr__(self, name, value):

  9. print(3)

  10. super().__setattr__(name, value)

  11. def __delattr__(self, name):

  12. print(4)

  13. super().__delattr__(name)

  14. >>> c = C()

  15. >>> c.x

答:在不上机的情况下,我相信80%以上的鱼油很难猜到正确的答案T_T

 
  1. >>> c = C()

  2. >>> c.x

  3. 2

  4. 1

  5. Traceback (most recent call last):

  6. File "<pyshell#31>", line 1, in <module>

  7. c.x

  8. File "<pyshell#29>", line 4, in __getattr__

  9. return super().__getattr__(name)

  10. AttributeError: 'super' object has no attribute '__getattr__'

为什么会如此显示呢?我们来分析下:首先 c.x 会先调用 __getattribute__() 魔法方法,打印 2;然后调用 super().__getattribute__(),找不到属性名 x,因此会紧接着调用 __getattr__() ,于是打印 1;但是你猜到了开头没猜到结局……当你希望最后以 super().__getattr__() 终了的时候,Python 竟然告诉你 AttributeError,super 对象木有 __getattr__ !!

求证:

 
  1. >>> dir(super)

  2. ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__self_class__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__thisclass__']

4. 请指出以下代码的问题所在:

 
  1. class Counter:

  2. def __init__(self):

  3. self.counter = 0

  4. def __setattr__(self, name, value):

  5. self.counter += 1

  6. super().__setattr__(name, value)

  7. def __delattr__(self, name):

  8. self.counter -= 1

  9. super().__delattr__(name)

答:初学者重写属性魔法方法很容易陷入的一个误区就是木有“观前顾后”。

以下注释:

 
  1. class Counter:

  2. def __init__(self):

  3. self.counter = 0 # 这里会触发 __setattr__ 调用

  4. def __setattr__(self, name, value):

  5. self.counter += 1

  6. “””既然需要 __setattr__ 调用后才能真正设置 self.counter 的值,所以这时候 self.counter 还没有定义,所以没法 += 1,错误的根源。”””

  7. super().__setattr__(name, value)

  8. def __delattr__(self, name):

  9. self.counter -= 1

  10. super().__delattr__(name)


动动手

0. 按要求重写魔法方法:当访问一个不存在的属性时,不报错且提示“该属性不存在!”

代码清单:

 
  1. >>> class Demo:

  2. def __getattr__(self, name):

  3. return '该属性不存在!'

  4. >>> demo = Demo()

  5. >>> demo.x

  6. '该属性不存在!'

1. 编写 Demo 类,使得下边代码可以正常执行:

 
  1. >>> demo = Demo()

  2. >>> demo.x

  3. 'FishC'

  4. >>> demo.x = "X-man"

  5. >>> demo.x

  6. 'X-man'

代码清单:

 
  1. >>> class Demo:

  2. def __getattr__(self, name):

  3. self.name = 'FishC'

  4. return self.name

2. 修改上边【测试题】第 4 题,使之可以正常运行:编写一个 Counter 类,用于实时检测对象有多少个属性。

程序实现如下:

 
  1. >>> c = Counter()

  2. >>> c.x = 1

  3. >>> c.counter

  4. 1

  5. >>> c.y = 1

  6. >>> c.z = 1

  7. >>> c.counter

  8. 3

  9. >>> del c.x

  10. >>> c.counter

  11. 2

代码清单:

 
  1. class Counter:

  2. def __init__(self):

  3. super().__setattr__('counter', 0)

  4. def __setattr__(self, name, value):

  5. super().__setattr__('counter', self.counter + 1)

  6. super().__setattr__(name, value)

  7. def __delattr__(self, name):

  8. super().__setattr__('counter', self.counter - 1)

  9. super().__delattr__(name)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值