什么是魔术方法
在Python中,所有以 __ 双下划线包起来的方法,都统称为 Magic Method 魔术方法,也叫双下划线方法
有哪些重要的魔术方法?
__new__
https://www.cnblogs.com/poloyy/p/15236309.html
__init__
https://www.cnblogs.com/poloyy/p/15189562.html
__str__
https://www.cnblogs.com/poloyy/p/15202541.html
__repr__
https://www.cnblogs.com/poloyy/p/15250973.html
__del__
https://www.cnblogs.com/poloyy/p/15192098.html
__call__
https://www.cnblogs.com/poloyy/p/15253366.html
其他比较常见的魔术方法
__len__
len() 调用对象会返回 __len__ 方法 return 的值,必须返回 integer
class A:
def __len__(self):
return 4
a = A()
print(len(a))
# 输出结果
4
__hash__
hash() 调用对象会返回 __hash__ 方法 return 的值,必须返回 integer
# __hash__
class A:
def __hash__(self):
return 123456
a = A()
print(hash(a))
# 输出结果
123456
__eq__
定义等于号的行为:x == y
class A:
def __init__(self):
self.a = 1
self.b = 2
def __eq__(self, obj):
print("call eq method.")
if self.a == obj.a and self.b == obj.b:
return True
a = A(