一、__init__和__del__
__init__主要是实例初始化, __del__相当于析构器
#/usr/bin/env python #-*- coding:utf-8 -*- class test(object): #实例初始化 def __init__(self): print "call __init__" #析构器 def __del__(self): print "call __del__" t=test()
call __init__ call __del__
init在实例化的时候调用,del在对象销毁时自动调用,一般类中都默认带有__del__不需要自己声明
二、 __new__和__init__
官网解释:
If __new__() returns an instance of
cls
, then the new instance’s __init__()
method will be invoked like __init__(
self
[, ...]), where
self
is
the new instance
and
the remaining arguments are the same as were passed to __new__().
如果__new__()返回cls的实例,则新实例的__init__()方法会像__init__(self[,...])调用,其中self是新实例,其他的参数和传给__new__()中的一样
If __new__() does
not
return
an instance of
cls
, then the new instance’s __init__() method will
not
be invoked.
如果 __new__()不返回实例,则__init__()不会被调用
1、
__new__ 是在__init__之前被调用的特殊方法,不返回实例
class A(object): def __init__(self): print "call __init__" def __new__(self): print "call __new__" a=A()——
call __new__
2、返回实例
class A(object): def __init__(self,x=0): print "call __init__" self.x=x def __new__(cls): print "call __new__" #返回cls的实例 return super(A,cls).__new__(cls) a=A()
call __new__ call __init__
2种方法刚好验证官网的解释,另外
__init__只是用来将传入的参数初始化给对象
,
__new__
很少用到
,除非你希望能够控制对象的创建。
三、__call__
类中定义了__call__ ()方法,表明类可以作为方法被调用
class B(object): #define __call__ def __call__(self,x=0): print "call __call__()" #value that the method returns return x #instance b=B() #invoked as a method b() print b(1)
call __call__() call __call__() 1
可以看出作为方法调用时获得的返回值为__call__()中返回的值。
四、其他的一些基本的定制魔法方法
#/usr/bin/env python #-*- coding:utf-8 -*- #instance class C(object): #内建str()以及print语句 def __str__(self): print "call __str__" return "class C __str__" #内建repr()和操作符 def __repr__(self): print "call __repr__" return "class C __repr__" #内建unicode() def __unicode__(self): print "call __unicode__" return "call C __unicode__" #内建bool() def __nozero__(self): print "call __nozeto__" #内建len() def __len__(self): print "call __len__" return 1 c=C() #首先 c 会调用__str__中的print #print c 会答应__str__方法返回值 print c #repr(c)的时候调用 __repr__方法中的print #print repr(c)会打印__repr__方法的返回值 print repr(c) #unicode(c)的时候调用 __unicode__方法中的print #print unicode(c)会打印__unicode__方法的返回值 print unicode(c) #len(c)的时候调用 __len__方法中的print #print len(c)会打印__len__方法的返回值 print len(c) #bool(c)的时候调用 __len__方法中的print #print bool(c)如果len(c)为0则返回False,非0则为True print bool(c)
结果:
call __str__ class C __str__ call __repr__ class C __repr__ call __unicode__ call C __unicode__ call __len__ 1 call __len__ True