繁体   English   中英

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

[英]Complex operations with Python (pygame.math.Vector2)

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

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

结果:

[1,2]
[4,8]

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

但是,如果我确实给x指定了一个简单的元组: x = (1, 2) ,而不是Vector2 ,我得到了错误:

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

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

可以做类似的事情(也可以查看评论):

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)

输出:

(5, 10)
(3.5, 6.0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM