python入门(坐标相加)

代码:

  1 #coding=utf-8
  2 class D2_point(object):
  3         def __init__(self,x,y):
  4                 print '***init'
  5                 self.x = x
  6                 self.y = y
  7 
  8         def __add__(self,oth):
  9                 print '***add'
 10                 return D2_point(self.x + oth.x,self.y + oth.y)
 11 
 12         def info(self):
 13                 print '***info'
 14                 print(self.x,self.y)
 15 
 16 class D3_point(D2_point):
 17         def __init__(self,x,y,z):
 18                 print '3Dinit'
 19                 super(D3_point,self).__init__(x,y)      #python2 中,super()需指定子类的继承
 20                 self.z = z
 21 
 22         def __add__(self,oth):
 23                 print '3Dadd'
 24                 return D3_point(self.x + oth.x,self.y + oth.y,self.z + oth.z)
 25 
 26         def info(self):
 27                 print '3Dinfo'
 28                 print(self.x,self.y,self.z)
 29 
 30 def myadd(a,b):         #注意此处是def,而不是class
 31         print '***myadd'
 32         return a + b
 33 
 34 if __name__ == '__main__':
 35         myadd(D2_point(1,2),D2_point(3,4)).info()
 36         #myadd(D3_point(1,2,3),D3_point(4,5,6)).info()

执行1:



执行2:



代码:

  1 #coding=utf-8
  2 class D2_point(object):
  3         def __init__(self,x,y):
  4                 print '***init'
  5                 self.x = x
  6                 self.y = y
  7 
  8         def __add__(self,oth):
  9                 print '***add'
 10                 return D2_point(self.x + oth.x,self.y + oth.y)
 11 
 12         def info(self):
 13                 print '***info'
 14                 print(self.x,self.y)
 15 
 16 class D3_point(D2_point):
 17         def __init__(self,x,y,z):
 18                 print '3Dinit'
 19                 #super(D3_point,self).__init__(x,y)     #python2 中,super()需指定子类的继承
 20                 self.x = x
 21                 self.y = y
 22                 self.z = z
 23 
 24         def __add__(self,oth):
 25                 print '3Dadd'
 26                 return D3_point(self.x + oth.x,self.y + oth.y,self.z + oth.z)
 27 
 28         def info(self):
 29                 print '3Dinfo'
 30                 print(self.x,self.y,self.z)
 31 
 32 def myadd(a,b):         #注意此处是def,而不是class
 33         print '***myadd'
 34         return a + b
 35 
 36 if __name__ == '__main__':
 37         #myadd(D2_point(1,2),D2_point(3,4)).info()
 38         myadd(D3_point(1,2,3),D3_point(4,5,6)).info()

执行2+:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值