本文共 1327 字,大约阅读时间需要 4 分钟。
python魔法方法:
类中被双下划线包围的方法,例如__init__(self, ...)
魔法方法是面向对象的python的一切
1 >>> class R(object):2 ... def __init__(self, x, y):3 ... self.x = x4 ... self.y = y5 ... 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 a9 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 = a10 >>> c = a11 >>> d = a12 >>> del b13 >>> del a14 >>> del d15 >>> 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 + b10 -2
python内置方法总结:
转载地址:http://gxabl.baihongyu.com/