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

时间:2018-09-29 01:22:53

标签: 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]

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

但是,如果我确实将简单的元组分配给x:(1, 2),而不是x = (1, 2),则会收到错误消息:

  

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

我的问题是:我什么时候可以在Python中执行这些复杂的操作?

1 个答案:

答案 0 :(得分:1)

可以做类似的事情(也请参见评论):

fmin

最好的还是创建一个类:

x = (1,2) # create a `tuple`
b = map(lambda x: x * 5,x) # do a `map` object for multiplying 5 to all of them
print(x) # print the `tuple`
t=iter((1,2)) # do an generator object using `iter`, so able to use `next` to access every next element
print(tuple(map(lambda x: x-next(t),b))) # do the `next` and another `map`, to subtract as you wanted

然后可以执行任何操作:

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)

输出:

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

也划分:

(5, 10)
(7, 12)

输出:

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