Python class 重载方法
Python面向对象的开发肯定离不开class,有点类似C语言的struct可以抽象描述对象并返回数据于方法。
例如,建立一个class描述笛卡尔坐标系中的点:
class point():
def __init__(self, x, y):
self.x = x
self.y = y
self.norm = (x * x + y * y) ** 0.5
def __repr__(self):
return ‘(%d,%d)‘%(self.x,self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return point(x,y)
def __sub__(self, other):
x = self.x - other.x
y = self.y - other.y
return point(x,y)
def __del__(self):
print(self,‘has gone‘)
a = point(2,3)
b = point(1,1)
print(a + b, a - b)
#Output:
#(3,4) (1,2)
#(1,2) has gone
#(3,4) has gone
#(2,3) has gone
#(1,1) has gone其中__init__为初始化方法,实例化时调用。__repr__为显示方法,被打印时调用__add__和__sub__分别重载加法和减法__del__为析构函数,对象被删除时调用
本例中可以通过输出信息观察析构的顺序
相关推荐
Dullonjiang 2020-08-15
SoShellon 2013-06-01
yawei 2019-12-31
jackalwb 2013-08-20
pythonxuexi 2011-08-13
xhao 2019-11-06
zgwyfz 2019-11-04
zhangpan 2019-10-30
visionzheng 2018-02-09
kick 2011-11-05
TLROJE 2017-02-06