__init__(self) 和 __new__(cls)方法
阿新 • • 發佈:2018-11-26
__init__(self) 和 __new__(cls)方法
class Dog(object):
def __init__(self):
'''
初始化,在__new__方法之後開始執行
'''
self.name = 'lijiang'
print(self.name)
def __del__(self):
print(self.name)
def __new__(cls):
'''
建立一個物件
'''
return object.__new__(cls)
def __str__(cls):
'''
初始化方法之後執行
'''
return '列印物件的特徵'
dog = Dog()
print(dog)
1)__new__是一個類方法,它返回的是一個例項
2)__init__是一個例項方法,它什麼都不返回
3)只有在__new__方法返回一個cls物件時,__init__方法才會被呼叫,否則__init__方法不會被呼叫