[英]Complex operations with Python (pygame.math.Vector2)
I'm learning Python and came across a complex expression that derives from pygame.Vector2
: 我正在学习Python,并遇到了一个源自
pygame.Vector2
的复杂表达式:
import pygame
x = pygame.math.Vector2 (1,2)
b = x * 5 - (1, 2)
print (x)
print (b)
Result: 结果:
[1,2]
[4,8]
In the above case, the same x * 5
operation is performed both for the 1
and 2
values of Vector2
, resulting in (5, 10) respectively; 在上述情况下,对
Vector2
的1
和2
值执行相同的x * 5
运算,分别得到(5,10); and then both results are subtracted from the tuple (1, 2)
, resulting in [4,8] 然后从元组
(1, 2)
中减去两个结果,得出[4,8]
However if I do assign a simple tuple to x: x = (1, 2)
, instead of Vector2
, I get the error: 但是,如果我确实给x指定了一个简单的元组:
x = (1, 2)
,而不是Vector2
,我得到了错误:
TypeError: unsupported operand type (s) for -: 'tuple' and 'tuple'
TypeError:-:“ tuple”和“ tuple”的不受支持的操作数类型
My question is: At what times in Python I can perform these complex operations? 我的问题是: 什么时候可以在Python中执行这些复杂的操作?
Can do something like (see comments too): 可以做类似的事情(也可以查看评论):
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
Best thing is still to create a class: 最好的还是创建一个类:
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))
Then now can do anything: 然后现在可以做任何事情:
x = MyClass((1,2))
b = x*5
print(b)
print(b-(1,2))
Output: 输出:
(5, 10)
(4, 8)
Also can do addition: 也可以做加法:
x = MyClass((1,2))
b = x*5
print(b)
print(b-(1,2)+(3,4))
Output: 输出:
(5, 10)
(7, 12)
Also division: 还划分:
x = MyClass((1,2))
b = x*5
print(b)
print((b-(1,2)+(3,4))/2)
Output: 输出:
(5, 10)
(3.5, 6.0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.