#类的内置方法,也叫双下方法、魔术方法
# __call__ 实例化对象加上(), 可以触发这个类的 __call__ 方法,类似实例化时自动执行的__init__()
class F1():
def __call__(self, *args, **kwargs):
print('call')
f1 = F1()
f1() # call
# __eq__ 判断对象是否相等
class F2():
pass
f2 = F2()
f22 = F2()
print(f2, f22) # 两个不同的类对象
print(f2 == f22) # False
class F3():
def __eq__(self, other):
if type(self) == type(other) and self.__dict__ == other.__dict__:
return True
else:
return False
f3 = F3()
f33 = F3()
print(f3, f33) # 还是两个不同的对象
print(f3 == f33) # True 重写__eq__ 方法后,判断类中接口相同则返回true
format_dit = {
'format1': '{obj.name}-{obj.sex}-{obj.age}',
'format2': '{obj.sex}-{obj.age}-{obj.name}',
'format3': '{obj.age}-{obj.name}-{obj.sex}'
}
class F4():
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def __eg__(self, other):
if type(self) == type(other) and self.__dict__ == other.__dict__:
return True
else:
return False
def __hash__(self):# 可hash对象必须要实现该方法
return hash(self.name + self.age)
def __str__(self):# 执行print()时会自动调用__str__方法,且必须返回str类型数据
return 'S'.join([self.name, self.sex])
def __repr__(self): # 与__str__相同,返回必须是str类型数据
return 'R'.join([self.name, self.sex])
# return self.age
def __format__(self, format_spec):
if not format_spec or format_spec not in format_dit:
format_spec = 'format1'
fmat = format_dit[format_spec]
return fmat.format(obj=self)
f4 = F4('T1', 'man', 11)
f44 = F4('T1', 'man', 11)
print(f4, f44) # T1Sman T1Sman
print(f4 == f44) # True 重写__eq__对比两个对象元素值
#hash()
L1 = [f4, f44]
print(L1) # [T1Rman, T1Rman]
print(set(L1)) # 实现__hash__方法后可用set() 集合进行去重
# __str__() 和 __repr__()
# 1、上面两次输出不一致,直接print使用str(),在容器中输出使用repr()
# 2、注释repr()方法后,下面示例在容器中输出时没有repr()时会使用默认输出,不会使用str(),所以注释repr()只保留str()时,输出对象内存地址
student = []
zs = F4('张三', '男', 11)
ls = F4('李四', '女', 12)
student.append(zs)
student.append(ls)
print(student) # [<__main__.F3 object at 0x7fb93fa116a0>, <__main__.F3 object at 0x7fb93fa11640>]
for i in student:
print(i) # 张三S男 李四S女 直接输出使用str()
#3、可以使用repr() 或 %r 执行对象的__repr__方法
print(repr(zs)) # 张三R男
print('111 %r' % ls) # 111 李四R女
#4、可以使用str() 和 %s 执行对象的 __str__方法
print(str(zs)) # 张三S男
print('222 %s' % ls) # 222 李四S女
# 注释掉__str__ 方法后,str() 和 %s 会使用 __repr__
# __format__ 自定义格式化输出
print(format(ls, 'format1')) # 李四-女-12
print(format(ls, 'format2')) # 女-12-李四
print(format(ls, 'format3')) # 12-李四-女
print(format(ls, 'test')) # 李四-女-12 条件判断设置了默认值