1. python中的魔法方法, 類似__init__, __str__等等,這些內置好的特定的方法進行特定的操作時會自動被調用
2. __init__的使用方法
class 類名(object):
def __init__(self):
print("hhahhah")
對象1 = 類名()
打印結果:hhahhah
說明init的方法實例化對象的時候會自動初始化調用
3. __str__的使用方法
class 類名(object):
def __str__(self):
return "hello world"
對象1 = 類名()
print(對象1)
打印結果:hello world
說明__str__方法會重寫原來的方法重寫返回自定義的代碼
4. __del__的方法使用
class 類名(object):
def __del__(self):
print("%s已經在內存中消失"%self)
對象1 = 類名()
del(對象1)
print("程序最后的代碼")
打印輸出:
__main__.類名 object at 0x000002B9AA1BC160>已經在內存中消失
程序最后的代碼
說明__del__的方法會在創建的對象消失后運行