0. 请写下这一节课你学习到的内容:格式不限,回忆并复述是加强记忆的好方式!
我们这节课说说魔法方法关于属性访问的应用。我们知道可以使用点操作符(.)的形式去访问对象属性。我们在类与对象相关的BIF这一节中,我们可以使用几个BIF有礼貌的去访问属性,例如:
-
>>> class C:
-
def __init__(self):
-
self.x = 'x-man'
-
>>> c = C()
-
>>> c.x
-
'x-man'
-
>>> getattr(c, 'x', '没有这个属性')
-
'x-man'
-
>>> getattr(c, 'y', '没有这个属性')
-
'没有这个属性'
另外,我们还介绍过setattr, delattr 分别是设置属性和删除属性,忘了的话可以回头看一下笔记。然后还介绍了property函数的用法,property使得我们以属性的方法去访问属性。例如:
-
>>> class C:
-
def __init__(self, size = 10):
-
self.size = size
-
def getSize(self):
-
return self.size
-
def setSize(self, value):
-
self.size = value
-
def delSize(self):
-
del self.size
-
x = property(getSize, setSize, delSize)
-
>>> c = C()
-
>>> c.x
-
10
-
>>> c.x = 1
-
>>> c.size
-
1
-
>>> del c.x
-
>>> c.size
-
Traceback (most recent call last):
-
File "<pyshell#24>", line 1, in <module>
-
c.size
-
AttributeError: 'C' object has no attribute 'size'
关于属性访问也有相应的魔法方法来管理,通过这些魔法方法的重写可以随心所欲的控制对象的属性访问。下面是今天要讲解的四个魔法方法:
(一)__getattr__(self, name)
–定义当用户试图获取一个不存在的属性时的行为
(二)__getattribute__(self, name)
–定义当该类的属性被访问时的行为
(三)__setattr__(self, name, value)
–定义当一个属性被设置时的行为
(四)__delattr__(self, name)
–定义当一个属性被删除时的行为
也就是说,我们只要重写以上四个魔法方法,就可以空置对象的属性访问了,我们举例说明来测试一下这四个魔法方法的前后关系、因果关系:
-
>>> class C:
-
def __getattr__(self, name):
-
print("getattr")
-
def __getattribute__(self, name):
-
print("getattribute")
-
return super().__getattribute__(name)
-
def __setattr__(self, name, value):
-
print("setatrtr")
-
super().__setattr__(name, value)
-
def __delattr__(self, name):
-
print("delattr")
-
super().__delattr__(name)
-
>>> c = C()
-
>>> c.x
-
getattribute
-
getattr
-
>>> c.x = 1
-
setatrtr
-
>>> c.x
-
getattribute
-
1
-
>>> del c.x
-
delattr
-
>>> c.x
-
getattribute
-
getattr
我们通过 print() 来在调用该魔法方法的时候打印一下,这是最好的调试方式。第一次c.x 的时候,对象是没有任何属性的,此时会先访问 getattribute,当属性不存在时,再去访问 getattr,设置属性时访问 setattr,删除属性时访问 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.name = value
-
def getArea(self):
-
return self.width * self.height
-
============ RESTART: C:/Users/XiangyangDai/Desktop/上课代码/45-1.py ============
-
>>> r = Rectangle(4, 5)
-
Traceback (most recent call last):
-
File "<pyshell#50>", line 1, in <module>
-
r = Rectangle(4, 5)
-
File "C:/Users/XiangyangDai/Desktop/上课代码/45-1.py", line 3, in __init__
-
self.width = width
-
File "C:/Users/XiangyangDai/Desktop/上课代码/45-1.py", line 10, in __setattr__
-
self.name = value
-
File "C:/Users/XiangyangDai/Desktop/上课代码/45-1.py", line 10, in __setattr__
-
self.name = value
-
..........
当我们运行并初始化时,就会进入死循环,这是为什么呢?这是因为初始化时,就会调用 __setattr__魔法方法,然后就会执行 self.name = value,而这个又会调用 __setattr__魔法方法,然后就进入死循环了,解决方法是什么呢?
就是把 self.name = value 这条语句改为调用基类的 __setattr__魔法方法(未被改写的魔法方法)。如下:
-
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:
-
super().__setattr__(name, value)
-
def getArea(self):
-
return self.width * self.height
-
>>> r = Rectangle(4, 5)
-
>>> r.height
-
5
-
>>> r.width
-
4
-
>>> r.getArea()
-
20
-
>>> r.square = 10
-
>>> r.width
-
10
-
>>> r.height
-
10
-
>>> r.getArea()
-
100
除了 __setattr__魔法方法,__getattribute__魔法方法也会陷入死循环的陷阱,如果一直去获得,就会重复的获得,死循环。推荐的解决方法就是使用基类的方法去设置、去获得。
测试题
0. 请问以下代码的作用是什么?这样写正确吗?(如果不正确,请改正)
-
def __setattr__(self, name, value):
-
self.name = value + 1
答:这段代码试图在对象的属性发生赋值操作的时候,将实际的值 +1赋值给相应的属性。但这么写法是错误的,因为每当属性被赋值的时候, __setattr__() 会被调用,而里边的 self.name = value + 1 语句又会再次触发 __setattr__() 调用,导致无限递归。
代码应该这样写:
-
def __setattr__(self, name, value):
-
self.__dict__[name] = value + 1
或者:
-
def __setattr__(self, name, value):
-
super().__setattr__(name, value+1)
1. 自定义该类的属性被访问的行为,你应该重写哪个魔法方法?
答:__getattribute__(self, name)
2. 在不上机验证的情况下,你能推断以下代码分别会显示什么吗?
-
>>> class C:
-
def __getattr__(self, name):
-
print(1)
-
def __getattribute__(self, name):
-
print(2)
-
def __setattr__(self, name, value):
-
print(3)
-
def __delattr__(self, name):
-
print(4)
-
>>> c = C()
-
>>> c.x = 1
-
# 位置一,请问这里会显示什么?
-
>>> print(c.x)
-
# 位置二,请问这里会显示什么?
答:位置一会显示 3,因为 c.x = 1 是赋值操作,所以会访问 __setattr__() 魔法方法;位置二会显示 2 和 None,因为 x 是属于实例对象 c 的属性,所以 c.x 是访问一个存在的属性,因此会访问 __getattribute__() 魔法方法,但我们重写了这个方法,使得它不能按照正常的逻辑返回属性值,而是打印一个 2 代替,由于我们没有写返回值,所以紧接着返回 None 并被 print() 打印出来。
3. 在不上机验证的情况下,你能推断以下代码分别会显示什么吗?
-
>>> class C:
-
def __getattr__(self, name):
-
print(1)
-
return super().__getattr__(name)
-
def __getattribute__(self, name):
-
print(2)
-
return super().__getattribute__(name)
-
def __setattr__(self, name, value):
-
print(3)
-
super().__setattr__(name, value)
-
def __delattr__(self, name):
-
print(4)
-
super().__delattr__(name)
-
>>> c = C()
-
>>> c.x
答:在不上机的情况下,我相信80%以上的鱼油很难猜到正确的答案T_T
-
>>> c = C()
-
>>> c.x
-
2
-
1
-
Traceback (most recent call last):
-
File "<pyshell#31>", line 1, in <module>
-
c.x
-
File "<pyshell#29>", line 4, in __getattr__
-
return super().__getattr__(name)
-
AttributeError: 'super' object has no attribute '__getattr__'
为什么会如此显示呢?我们来分析下:首先 c.x 会先调用 __getattribute__() 魔法方法,打印 2;然后调用 super().__getattribute__(),找不到属性名 x,因此会紧接着调用 __getattr__() ,于是打印 1;但是你猜到了开头没猜到结局……当你希望最后以 super().__getattr__() 终了的时候,Python 竟然告诉你 AttributeError,super 对象木有 __getattr__ !!
求证:
-
>>> dir(super)
-
['__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. 请指出以下代码的问题所在:
-
class Counter:
-
def __init__(self):
-
self.counter = 0
-
def __setattr__(self, name, value):
-
self.counter += 1
-
super().__setattr__(name, value)
-
def __delattr__(self, name):
-
self.counter -= 1
-
super().__delattr__(name)
答:初学者重写属性魔法方法很容易陷入的一个误区就是木有“观前顾后”。
以下注释:
-
class Counter:
-
def __init__(self):
-
self.counter = 0 # 这里会触发 __setattr__ 调用
-
def __setattr__(self, name, value):
-
self.counter += 1
-
“””既然需要 __setattr__ 调用后才能真正设置 self.counter 的值,所以这时候 self.counter 还没有定义,所以没法 += 1,错误的根源。”””
-
super().__setattr__(name, value)
-
def __delattr__(self, name):
-
self.counter -= 1
-
super().__delattr__(name)
动动手
0. 按要求重写魔法方法:当访问一个不存在的属性时,不报错且提示“该属性不存在!”
代码清单:
-
>>> class Demo:
-
def __getattr__(self, name):
-
return '该属性不存在!'
-
>>> demo = Demo()
-
>>> demo.x
-
'该属性不存在!'
1. 编写 Demo 类,使得下边代码可以正常执行:
-
>>> demo = Demo()
-
>>> demo.x
-
'FishC'
-
>>> demo.x = "X-man"
-
>>> demo.x
-
'X-man'
代码清单:
-
>>> class Demo:
-
def __getattr__(self, name):
-
self.name = 'FishC'
-
return self.name
2. 修改上边【测试题】第 4 题,使之可以正常运行:编写一个 Counter 类,用于实时检测对象有多少个属性。
程序实现如下:
-
>>> c = Counter()
-
>>> c.x = 1
-
>>> c.counter
-
1
-
>>> c.y = 1
-
>>> c.z = 1
-
>>> c.counter
-
3
-
>>> del c.x
-
>>> c.counter
-
2
代码清单:
-
class Counter:
-
def __init__(self):
-
super().__setattr__('counter', 0)
-
def __setattr__(self, name, value):
-
super().__setattr__('counter', self.counter + 1)
-
super().__setattr__(name, value)
-
def __delattr__(self, name):
-
super().__setattr__('counter', self.counter - 1)
-
super().__delattr__(name)