python入门(坐标相加)

2023-01-31 03:01:35 坐标 入门 相加

代码:

  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+:




相关文章