__str__:用于在print(对象)时,直接打印__str__的返回值
1 class Animal: 2 def __init__(self, name): 3 self.name = name 4 def __str__(self): 5 return self.name 6 7 d = Animal("dog") 8 print(d)
__fun_name:私有方法
1 class Animal: 2 def __init__(self, name): 3 self.name = name 4 def eat(self): 5 self.__test() 6 print("吃东西") 7 #test为私有方法,不能在类外部调用 8 def __test(self): 9 print("debug") 10 11 d = Animal("dog") 12 # 提示 AttributeError: ‘Animal‘ object has no attribute ‘__test‘ 13 # d.__test() 14 d.eat()
__del__:对象销毁时调用的方法
1 class Animal: 2 def __init__(self, name): 3 self.name = name 4 def __del__(self): 5 print("---go die---") 6 7 d = Animal("dog") 8 dd = d 9 del d #仅仅删除一个引用计数,引用计数为0时才销毁对象,并且调用__del__方法 10 del dd 11 print("******")
原文地址:https://www.cnblogs.com/xhcdream/p/8251684.html
时间: 2024-11-09 06:02:12