簡體   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