__str__,__resp__,__eq__,__hash__,__bool__,__del__
class Mydate:
def __init__(self,year: int,month: int,day: int):
self.year = year
self.month = month
self.day = day
'''
__str__方法可以自己定义当对象被打印或者str函数调用时的输出格式
主要是针对用户来使用的
'''
def __str__(self):
print("str is called")
return (f"{self.year}-{self.month}-{self.day}")
'''
__repr__方法与__str__方法使用类似,主要针对计算机和程序员使用的
常用的场景比如日志输出,这样更容易对程序进行维护
'''
def __repr__(self):
print("repr is called")
return (f"MyDate:{self.year}-{self.month}-{self.day}")
'''
__eq__ 自定义两个对象进行比较的内容和逻辑,other参数是另外一个对象
'''
def __eq__(self, other):
if not isinstance(other,Mydate): # isinstence函数用来判断一个对象是否是已知类型
return False
if self.year == other.year and self.month == other.month and self.day == other.day:
print("__eq__ is called")
return True
'''
自定义实例对象的哈希值
hash()函数 使用时调用这个方法
把对象放入字典或者set集合中,__hash__也会被调用
'''
def __hash__(self):
print("__hash__ is called")
return hash(self.year + self.month*100 + self.day*101)
'''
当bool()函数使用时,调用__bool__方法,可以自定义返回的逻辑结果
'''
def __bool__(self):
print("__bool__ is called")
# if self.year > 2022:
# return True
# else:
# return False
return self.year > 2022
'''
当对象不适用被当做垃圾回收的时候,__del__方法被调用
'''
def __del__(self):
print("__del__ is called")
def main():
date_1 = Mydate(2023,12,22)
print(date_1)
print(repr(date_1))
date_2 = Mydate(2023,12,22)
date_3 = date_1
date_5 = Mydate(2022,12,22)
date_5 = None # 对象指向空,__del__方法被调用
print(date_1 is date_3) # is是比较两个对象是否同时指向一个内存地址
print(date_1 == date_2) # == 才能调用__eq__方法
date_set = set()
date_set.add(date_1) # 把对象放入字典或者set集合中,__hash__就会被调用
print(hash(date_1)) # 调用__hash__方法
date_4 = Mydate(2021,12,22)
print(bool(date_4))
print(bool(date_1))
if __name__ == "__main__":
main()