Python魔术方法
__开头,__结尾的方法就是魔术方法.
1.__str__格式化输出对象
__repr__表示对象本身
class A:
def __str__(self):
return 'This is A'
# 表示对象本身
def __repr__(self):
return "I'm a A"
a = A()
print(a) # This is A
a # I'm a A
2.__init__和 __new__
__init__ 初始化实例,无返回值
__new__创建一个实例,并返回类的实例.
__new__是一个特殊的类方法,不需要使用@classmethod来装饰.
使用__new__单例模式
# 借助__new__方法实现单例模式
class Singleton:
instance = None
def __new__(cls, *args, **kwargs):
# 判断实例对象是否已经存在
if cls.instance is None:
# 说明实例对象不存在.需要创建
cls.instance = super().__new__(Singleton, *args, **kwargs)
return cls.instance
s = Singleton()
s2 = Singleton()
s is s2
out: True
display(id(s), id(s2))
out: 78960288 78960288
3.数学运算、比较运算
运算符重载
+:__add__(value)
-: __sub__(value) substract
*: __mul__(value) mulply
/: __truediv__(value) (Python 3.x), __div__(value) (Python 2.x) divide
//: __floordiv__(value)
%: __mod__(value)
&: __and__(value)
|:__or__(value)
# 自定义字典的加法
class Dict(dict):
# 实现加法
def __add__(self, other):
# 判断other是否是字典.
if isinstance(other, dict):
new_dict = {}
new_dict.update(self)
new_dict.update(other)
return new_dict
else:
raise TypeError('not a dict')
d1 = {1: 11, 2: 22}
d2 = {1: 111, 2: 222, 3:333}
dd1 = Dict(d1)
dd1 + d2