python中有二個(gè)特殊的方法new 和 init 方法浦夷。聽(tīng)黃哥來(lái)講解益涧。
init 方法為初始化方法, new方法才是真正的構(gòu)造函數(shù)软瞎。
1闯割、new方法默認(rèn)返回實(shí)例對(duì)象供init方法、實(shí)例方法使用省店。
請(qǐng)看下面的代碼嚣崭。
# coding:utf-8
class Foo(object):
'''黃哥python培訓(xùn)蜘拉,黃哥所寫(xiě)'''
price = 50
def how_much_of_book(self, n):
print(self)
return self.price * n
foo = Foo()
print(foo.how_much_of_book(8))
print(dir(Foo))
分析上面的代碼,這個(gè)類實(shí)例化過(guò)程有鹿,F(xiàn)oo類繼承object類旭旭,繼承了object的new方法。
當(dāng)你沒(méi)有重載這個(gè)方法(通俗來(lái)說(shuō)葱跋,你沒(méi)有在Foo類中沒(méi)有寫(xiě)new方法)持寄,F(xiàn)oo實(shí)例化是默認(rèn)自動(dòng)調(diào)用父類new方法,這個(gè)方法返回值為類的實(shí)例(self),提供這個(gè)函數(shù)how_much_of_book娱俺,默認(rèn)的第一個(gè)參數(shù)self稍味。
# coding:utf-8
class Foo(object):
price = 50
def __new__(cls, *agrs, **kwds):
inst = object.__new__(cls, *agrs, **kwds)
print(inst)
return inst
def how_much_of_book(self, n):
print(self)
return self.price * n
foo = Foo()
print(foo.how_much_of_book(8))
# <__main__.Foo object at 0x1006f2750>
# <__main__.Foo object at 0x1006f2750>
# 400
請(qǐng)看上面代碼,F(xiàn)oo類中重載了new方法荠卷,它的返回值為Foo類的實(shí)例對(duì)象模庐。
2、init 方法為初始化方法油宜,為類的實(shí)例提供一些屬性或完成一些動(dòng)作掂碱。
# coding:utf-8
class Foo(object):
def __new__(cls, *agrs, **kwds):
inst = object.__new__(cls, *agrs, **kwds)
print(inst)
return inst
def __init__(self, price=50):
self.price = price
def how_much_of_book(self, n):
print(self)
return self.price * n
foo = Foo()
print(foo.how_much_of_book(8))
# <__main__.Foo object at 0x1006f2750>
# <__main__.Foo object at 0x1006f2750>
# 400
3、new 方法創(chuàng)建實(shí)例對(duì)象供init 方法使用慎冤,init方法定制實(shí)例對(duì)象疼燥。
new 方法必須返回值,init方法不需要返回值蚁堤。(如果返回非None值就報(bào)錯(cuò))
4醉者、一般用不上new方法,new方法可以用在下面二種情況披诗。
new() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.
繼承不可變數(shù)據(jù)類型時(shí)需要用到new方法(like int, str, or tuple) 撬即。
# coding:utf-8
class Inch(float):
"Convert from inch to meter"
def __new__(cls, arg=0.0):
return float.__new__(cls, arg*0.0254)
print(Inch(12))
用在元類,定制創(chuàng)建類對(duì)象呈队。
# coding:utf-8
'''來(lái)自http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example'''
class MetaClass(type):
def __new__(meta, name, bases, dct):
print '-----------------------------------'
print "Allocating memory for class", name
print meta
print bases
print dct
return super(MetaClass, meta).__new__(meta, name, bases, dct)
def __init__(cls, name, bases, dct):
print '-----------------------------------'
print "Initializing class", name
print cls
print bases
print dct
super(MetaClass, cls).__init__(name, bases, dct)
class Myclass(object):
__metaclass__ = MetaClass
def foo(self, param):
print param
p = Myclass()
p.foo("hello")
# -----------------------------------
# Allocating memory for class Myclass
# <class '__main__.MetaClass'>
# (<type 'object'>,)
# {'__module__': '__main__', 'foo': <function foo at 0x1007f6500>, '__metaclass__': <class '__main__.MetaClass'>}
# -----------------------------------
# Initializing class Myclass
# <class '__main__.Myclass'>
# (<type 'object'>,)
# {'__module__': '__main__', 'foo': <function foo at 0x1007f6500>, '__metaclass__': <class '__main__.MetaClass'>}
# hello