Python的复杂操作(pygame.math.Vector2)

Python的复杂操作(pygame.math.Vector2),python,python-3.x,pygame,tuples,Python,Python 3.x,Pygame,Tuples,我正在学习Python,遇到了一个复杂的表达式,它源自pygame.Vector2: import pygame x = pygame.math.Vector2 (1,2) b = x * 5 - (1, 2) print (x) print (b) 结果: [1,2] [4,8] 在上述情况下,对Vector2的1和2值执行相同的x*5操作,分别得到(5,10);然后从元组(1,2)中减去这两个结果,得到[4,8] 但是,如果我确实为x分配了一个简单的元组:x=(1,2),而不是Vecto

我正在学习Python,遇到了一个复杂的表达式,它源自
pygame.Vector2

import pygame
x = pygame.math.Vector2 (1,2)
b = x * 5 - (1, 2)
print (x)
print (b)
结果:

[1,2]
[4,8]
在上述情况下,对
Vector2
1
2
值执行相同的
x*5
操作,分别得到(5,10);然后从元组
(1,2)
中减去这两个结果,得到[4,8]

但是,如果我确实为x分配了一个简单的元组:
x=(1,2)
,而不是
Vector2
,我会得到以下错误:

TypeError:-:“tuple”和“tuple”的操作数类型不受支持

我的问题是:在Python中,我什么时候可以执行这些复杂的操作?可以执行以下操作(也请参见注释):

最好还是创建一个类:

from __future__ import division
class MyClass:
   def __init__(self,t):
      self.t=t
   def __mul__(self,other):
      return MyClass(tuple(map(lambda x: x*other,self.t)))
   def __truediv__(self,other):
      return MyClass(tuple(map(lambda x: x/other,self.t)))
   def __sub__(self,other):
      gen=iter(other)
      return MyClass(tuple(map(lambda x: x-next(gen),self.t)))
   def __add__(self,other):
      gen=iter(other)
      return MyClass(tuple(map(lambda x: x+next(gen),self.t)))
   def __repr__(self):
      return str(tuple(self.t))
那么现在我们可以做任何事情:

x = MyClass((1,2))
b = x*5
print(b)
print(b-(1,2))
输出:

(5, 10)
(4, 8)
(5, 10)
(7, 12)
(5, 10)
(3.5, 6.0)
此外,您还可以执行以下操作:

x = MyClass((1,2))
b = x*5
print(b)
print(b-(1,2)+(3,4))
输出:

(5, 10)
(4, 8)
(5, 10)
(7, 12)
(5, 10)
(3.5, 6.0)
此外,该司:

x = MyClass((1,2))
b = x*5
print(b)
print((b-(1,2)+(3,4))/2)
输出:

(5, 10)
(4, 8)
(5, 10)
(7, 12)
(5, 10)
(3.5, 6.0)

Vector2
类实现了一个采用整数(以及其他类型)的
\uuuuuuuuuuuuuuuuuuuuuuuuuu()方法,以及一个采用元组的
\uuuuuuuuuuuuuuuuuuuuuu()方法。这些都不是自动发生的,类的实现者认为实现这些特性值得付出额外的努力。(请注意,元组无法合理地实现您尝试使用的减法操作,因为它与元组加法不兼容。)