一、概述:
python魔法方法:
类中被双下划线包围的方法,例如__init__(self, ...)
魔法方法是面向对象的python的一切
1 >>> class R(object): 2 ... def __init__(self, x, y): 3 ... self.x = x 4 ... self.y = y 5 ... def get(self): 6 ... return (self.x + self.y) 7 ... def getA(self): 8 ... return self.x * self.y
在实例化类时,__init__()并不是第一个被调用的函数,第一个被调用的函数是__new__();
1 >>> class Capstr(str): #str是不可改变对象 2 ... def __new__(cls, string): #自定义的重写__new__函数 3 ... string = string.upper() 4 ... return str.__new__(cls, string) 5 ... 6 ... 7 >>> a = Capstr("hello") 8 >>> print a 9 HELLO
__del__():相当于c++里面的析构函数;
1 >>> class C(object): 2 ... def __init__(self): 3 ... print "__init__ is calling" 4 ... def __del__(self): 5 ... print "__del__ is calling" 6 ... 7 >>> a = C() 8 __init__ is calling 9 >>> b = a 10 >>> c = a 11 >>> d = a 12 >>> del b 13 >>> del a 14 >>> del d 15 >>> del c #当引用个数为0时候,启用python垃圾回收机制,__del__方法被调用 16 __del__ is calling
python内置方法实例:
1 >>> class New_int(int): 2 ... def __add__(self, other): 3 ... return int.__sub__(self, other) 4 ... def __sub__(self, other): 5 ... return int.__add__(self, other) 6 ... 7 >>> a = New_int(3) 8 >>> b = New_int(5) 9 >>> a + b 10 -2
python内置方法总结:http://www.cnblogs.com/hongfei/p/3858256.html