Day 15-16
魔法方法
魔法方法是面向对象的 Python 的一切,它们总是被双下划线包围,并且总能够在适当的时候被自动调用。
一般情况下,魔法方法的第一个参数应为cls
(类方法) 或者self
(实例方法)。
cls
:代表一个类的名称self
:代表一个实例对象的名称
下面我们来介绍这些魔法方法。
1、基本魔法方法
__init__(self[, ...])
构造器,当一个实例被创建的时候调用的初始化方法
class QAQ:
def __init__(self, a, b):
self.a = a
self.b = b
def AAA(self):
return(self.a - self.b)
def BBB(self):
return(self.a * self.b)
x = QAQ(10,5)
print(x.AAA()) # 5
print(x.BBB()) # 50
__new__(cls[, ...])
__new__
是在一个对象实例化的时候所调用的第一个方法,在调用 __init__
初始化前,先调用__new__
。
__new__
至少要有一个参数cls
,代表要实例化的类,此参数在实例化时由 Python 解释器自动提供,后面的参数直接传递给__init__
。
__new__
对当前类进行了实例化,并将实例返回,传给__init__
的self
。但是,执行了__new__
,并不一定会进入__init__
,只有__new__
返回了,当前类cls
的实例,当前类的__init__
才会进入。如下例:
class QAQ(object):
def __init__(self, a):
print("first")
self.a = a
def __new__(cls, *args, **kwargs):
print("first new")
print(cls)
return object.__new__(cls)
class PPP(QAQ):
def __init__(self, b):
print("second")
self.b = b
def __new__(cls, *args, **kwargs):
print("second new")
print(cls)
return super().__new__(cls, *args, **kwargs)
b = PPP(1)
'''
second new
<class '__main__.PPP'>
first new
<class '__main__.PPP'>
second
'''
对比
class QAQ(object):
def __init__(self, a):
print("first")
self.a = a
def __new__(cls, *args, **kwargs):
print("first new")
print(cls)
return object.__new__(cls)
class PPP(QAQ):
def __init__(self, b):
print("second")
self.b = b
def __new__(cls, *args, **kwargs):
print("second new")
print(cls)
return super().__new__(QAQ, *args, **kwargs)
b = PPP(1)
'''
second new
<class '__main__.PPP'>
first new
<class '__main__.QAQ'>
'''
若__new__
没有正确返回当前类cls的实例,那__init__
是不会被调用的,即使是父类的实例也不行,将没有__init__
被调用。但是加上super().__init__()
就可以输出了。例子如下:
class QAQ(object):
def __init__(self, a):
print("first")
self.a = a
def __new__(cls, *args, **kwargs):
print("first new")
print(cls)
return object.__new__(cls)
class PPP(QAQ):
def __init__(self, b):
print("second")
self.b = b
super().__init__(b)
def __new__(cls, *args, **kwargs):
print("second new")
print(cls)
return super().__new__(cls, *args, **kwargs)
b = PPP(1)
'''
second new
<class '__main__.PPP'>
first new
<class '__main__.PPP'>
second
first
'''
可利用__new__
实现单例模式。例如:
class PPP:
pass
a = PPP()
print(id(a)) # 2487158016600
b = PPP()
print(id(b)) # 2487158017720
class PPP:
__ttt = None # 定义一个类属性做判断
def __new__(cls):
if cls.__ttt is None:
cls.__ttt = object.__new__(cls)
return cls.__ttt
else:
return cls.__ttt
a = PPP()
print(id(a)) # 2487159787760
b = PPP()
print(id(b)) # 2487159787760
__new__
方法主要是当你继承一些不可变的 class
时(比如int
, str
, tuple
), 提供给你一个自定义这些类的实例化过程的途径。
class QAQ(str):
def __new__(cls, string):
string = string.upper()
return str.__new__(cls, string)
a = QAQ("ZZH")
print(a) # ZZH
__del__(self)
析构器,当一个对象将要被系统回收之时调用的方法。
class t:
def a(self):
print("a开始")
def __del__(self):
print("结束")
if __name__ == '__main__':
b = t()
b.a()
del b
# a开始
# 结束
__str__
和__repr__
__str__(self):
当你打印一个对象的时候,触发__str__
当你使用%s格式化的时候,触发__str__
str强转数据类型的时候,触发__str__
__repr__(self):
__repr__
是__str__
的备胎,有__str__
的时候执行__str__
,没有实现__str__
的时候,执行__repr__
__repr(obj)__
内置函数对应的结果是__repr__
的返回值
当你使用%r格式化的时候,触发__repr__
下面举一个例子:
class Dog:
"""创建一个类"""
def __init__(self, name, age):
"""在创建完对象之后 会自动调用, 它完成对象的初始化的功能"""
self.name = name
self.age = age
def __str__(self):
"""返回一个对象的描述信息"""
return "它的名字叫%s , 年龄是%d" % (self.name, self.age)
def __repr__(self):
"""返回一个对象的描述信息"""
return "Dog:(%s,%d)" % (self.name, self.age)
def eat(self):
print("%s喜欢吃狗粮!" % self.name)
def drink(self):
print("%s喜欢喝水!" % self.name)
def introduce(self):
print("名字是:%s, 年龄是:%d" % (self.name, self.age))
# 创建了一个对象
tom = Dog("KK", 4)
print(tom) # 它的名字叫KK , 年龄是4
print(str(tom)) # 它的名字叫KK , 年龄是4
print(repr(tom)) # Dog:(KK,4)
tom.eat() # KK喜欢吃狗粮!
tom.introduce() # 名字是:KK, 年龄是:4
__str__(self)
的返回结果可读性强。也就是说,__str__
的意义是得到便于人们阅读的信息。
__repr__(self)
的返回结果应更准确。__repr__
存在的目的在于调试,便于开发者使用。
import datetime
today = datetime.date.today()
print(str(today)) # 2019-10-11
print(repr(today)) # datetime.date(2019, 10, 11)
print('%s' %today) # 2019-10-11
print('%r' %today) # datetime.date(2019, 10, 11)
2、算术运算符
类型工厂函数,指的是不通过类而是通过函数来创建对象。
__add(self, other)__
定义加法的行为:+__sub(self, other)__
定义减法的行为:-__mul__(self, other)
定义乘法的行为:*__truediv__(self, other)
定义真除法的行为:/__floordiv__(self, other)
定义整数除法的行为://__mod__(self, other)
定义取模算法的行为:%__divmod__(self, other)
定义当被divmod()
调用时的行为__divmod__(a, b)
把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。__pow__(self, other[, module])
定义当被power()
调用或**
运算时的行为__lshift__(self, other)
定义按位左移位的行为:<<__rshift__(self, other)
定义按位右移位的行为:>>__and__(self, other)
定义按位与操作的行为:&__xor__(self, other)
定义按位异或操作的行为:^__or__(self, other)
定义按位或操作的行为:|
下面举个实例:
class M:
def __init__(self, x):
self.x = x
def __str__(self):
return 'M (%d)' % self.x
def __add__(self,other):
return M(self.x + other.x)
def __sub__(self,other):
return M(self.x - other.x)
def __mul__(self,other):
return M(self.x * other.x)
def __truediv__(self,other):
return M(self.x / other.x)
def __floordiv__(self,other):
return M(self.x // other.x)
def __mod__(self,other):
return M(self.x % other.x)
v1 = M(8)
v2 = M(5)
print (v1 + v2) # M (13)
print (v1 - v2) # M (3)
print (v1 * v2) # M (40)
print (v1 / v2) # M (1)
print (v1 // v2) # M (1)
print (v1 % v2) # M (3)
print(divmod(7, 2)) # (3, 1)
print(divmod(8, 2)) # (4, 0)
3、反算术运算符
反运算魔方方法,与算术运算符保持一一对应,不同之处就是反运算的魔法方法多了一个“r”。当文件左操作不支持相应的操作时被调用。
__radd__(self, other)
定义加法的行为:+__rsub__(self, other)
定义减法的行为:-__rmul__(self, other)
定义乘法的行为:*__rtruediv__(self, other)
定义真除法的行为:/__rfloordiv__(self, other)
定义整数除法的行为://__rmod__(self, other)
定义取模算法的行为:%__rdivmod__(self, other)
定义当被 divmod() 调用时的行为__rpow__(self, other[, module])
定义当被 power() 调用或 ** 运算时的行为__rlshift__(self, other)
定义按位左移位的行为:<<__rrshift__(self, other)
定义按位右移位的行为:>>__rand__(self, other)
定义按位与操作的行为:&__rxor__(self, other)
定义按位异或操作的行为:^__ror__(self, other)
定义按位或操作的行为:|
比如:在a + b
中,这里加数是a
,被加数是b
,因此是a
主动,反运算就是如果a
对象的__add__()
方法没有实现或者不支持相应的操作,那么 Python 就会调用b的__radd__()
方法。例如:
class QAQ(int):
def __radd__(self, other):
return int.__sub__(other, self) # 注意 self 在后面
a = QAQ(10)
b = QAQ(1)
print(a + b) # 11
print(1 + b) # 0
4、增量赋值运算符
__iadd__(self, other)
定义赋值加法的行为:+=__isub__(self, other)
定义赋值减法的行为:-=__imul__(self, other)
定义赋值乘法的行为:*=__itruediv__(self, other)
定义赋值真除法的行为:/=__ifloordiv__(self, other)
定义赋值整数除法的行为://=__imod__(self, other)
定义赋值取模算法的行为:%=__ipow__(self, other[, modulo])
定义赋值幂运算的行为:**=__ilshift__(self, other)
定义赋值按位左移位的行为:<<=__irshift__(self, other)
定义赋值按位右移位的行为:>>=__iand__(self, other)
定义赋值按位与操作的行为:&=__ixor__(self, other)
定义赋值按位异或操作的行为:^=__ior__(self, other)
定义赋值按位或操作的行为:|=
5、一元运算符
__neg__(self)
定义正号的行为:+x__pos__(self)
定义负号的行为:-x__abs__(self)
定义当被abs()
调用时的行为__invert__(self)
定义按位求反的行为:~x
6、属性访问
__getattr__(self, name)
: 定义当用户试图获取一个不存在的属性时的行为。__getattribute__(self, name)
:定义当该类的属性被访问时的行为(先调用该方法,查看是否存在该属性,若不存在,接着去调用__getattr__
)。__setattr__(self, name, value)
:定义当一个属性被设置时的行为。__delattr__(self, name)
:定义当一个属性被删除时的行为。
7、描述符
描述符就是将某种特殊类型的类的实例指派给另一个类的属性。
__get__(self, instance, owner)
用于访问属性,它返回属性的值。__set__(self, instance, value)
将在属性分配操作中调用,不返回任何内容。__del__(self, instance)
控制删除操作,不返回任何内容。
class MyDecriptor:
def __get__(self, instance, owner):
print('__get__', self, instance, owner)
def __set__(self, instance, value):
print('__set__', self, instance, value)
def __delete__(self, instance):
print('__delete__', self, instance)
class Test:
x = MyDecriptor()
t = Test()
t.x
# __get__ <__main__.MyDecriptor object at 0x000000CEAAEB6B00> <__main__.Test object at 0x000000CEABDC0898> <class '__main__.Test'>
t.x = 'x-man'
# __set__ <__main__.MyDecriptor object at 0x00000023687C6B00> <__main__.Test object at 0x00000023696B0940> x-man
del t.x
# __delete__ <__main__.MyDecriptor object at 0x000000EC9B160A90> <__main__.Test object at 0x000000EC9B160B38>
8、定制序列
容器类型的协议:
- 如果说你希望定制的容器是不可变的话,你只需要定义
__len__()
和__getitem()__
方法。 - 如果你希望定制的容器是可变的话,除了
__len__()
和__getitem__()
方法,你还需要定义__setitem__()
和__delitem()__
两个方法。 __len__(self)
定义当被len()调用时的行为(返回容器中元素的个数)。__getitem__(self, key)
定义获取容器中元素的行为,相当于self[key]
。__setitem__(self, key, value)
定义设置容器中指定元素的行为,相当于self[key] = value
。__delitem__(self, key)
定义删除容器中指定元素的行为,相当于del self[key]
。
9、迭代器
iter(object)
函数用来生成迭代器。next(iterator[, default])
返回迭代器的下一个项目。iterator
– 可迭代对象default
– 可选,用于设置在没有下一个元素时返回该默认值,如果不设置,又没有下一个元素则会触发StopIteration
异常。
把一个类作为一个迭代器使用需要在类中实现两个魔法方法 __iter__()
与 __next__()
。
__iter__(self)
定义当迭代容器中的元素的行为,返回一个特殊的迭代器对象, 这个迭代器对象实现了__next()__
方法并通过StopIteration
异常标识迭代的完成。__next()__
返回下一个迭代器对象。StopIteration
异常用于标识迭代的完成,防止出现无限循环的情况,在__next()__
方法中我们可以设置在完成指定循环次数后触发StopIteration
异常来结束迭代。
总结:
本次学习内容较多,很多实例需要我们一个一个去尝试学习,这次学习的内容也较为重要,后面要多加复习巩固。
学习参考资料:
https://mp.weixin.qq.com/s?__biz=MzIyNDA1NjA1NQ==&mid=2651011513&idx=1&sn=42865ce577227fa514a1d80cce1d1848&chksm=f3e35e21c494d7370521c089fc7487eddc6b31d301289f294fd48908b8e9ef53128a8ab3a590&mpshare=1&scene=1&srcid=&sharer_sharetime=1572795901602&sharer_shareid=8c49d4226c319addceef298b781f6bb7&key=f0572ec07140f1609805d1083249b03f0fdd22fa7c0939e3173edca0dea461f860938a99c86a80b21c6fe015d57b458670ede9bc0be30fc6c0137aa9dacfe5a85bd8403451aa04d3607cf77ca4f63e7f&ascene=1&uin=MTgxNzI3MTY0MQ%3D%3D&devicetype=Windows+10&version=62060841&lang=zh_CN&pass_ticket=cqgG6LKpHPamX8RTGhLOOypD0TX%2FrVtIbMYnF4KiKe1wLfFCchgTR4mIFnp%2BNoV8
https://www.bilibili.com/video/av4050443