简体   繁体   中英

Round Bracket inside Round Bracket in Def Function

I am doing a pygame physics tutorial. However, when I try putting Round Bracket inside Round Bracket in Def Function, it says "Invalid Syntax". I could not find a answer anywhere.

def addVectors((angle1, length1), (angle2, length2)):

That only works in Python 2 sadly:

>$ python2
Python 2.7.18 (default, Mar  8 2021, 13:02:45) 
[GCC 9.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def addVectors((angle1, length1), (angle2, length2)):
...   pass
... 
>>> 
>$ python3
Python 3.8.8 (default, Apr 13 2021, 19:58:26) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def addVectors((angle1, length1), (angle2, length2)):
  File "<stdin>", line 1
    def addVectors((angle1, length1), (angle2, length2)):
                   ^
SyntaxError: invalid syntax

I suggest using a namedtuple :

from collections import namedtuple

Vector = namedtuple('Vector', ['angle', 'length'])

v1 = Vector(angle=1, length=1)
v2 = Vector(angle=2, length=1)

def addVectors(v1, v2):
    return Vector(v1.angle + v2.angle, v1.length + v2.length)

You are trying to pass a tuple by parameter but this way is the wrong syntax way. Try something like that:

def addVectors(*angles):
    for i in angles:
        print(i)

# addVectors((angle1, length1), (angle2, length2))
# (1, 2)
# (3, 4)

The * will unpack like a list and you can pass any size of parameters

Given your specific example, you can hopefully see why the syntax you are looking for is error prone. Imagine what happens when you accidentally mess up a single parenthesis 6 months from now. You have a couple of options to implement the same functionality trivially in Python 3 with fewer parentheses.

If you want the input to be four objects:

def addVectors(angle1, length1, angle2, length2):
    ...

and call as

self.angle, self.speed = addVectors(self.angle, self.speed, *gravity)

If you want two inputs, you can specify an explicit unpacking:

def addVectors(
    angle1, length1 = vector1
    angle2, length2 = vector2
    ...

and call it as

self.angle, self.speed = addVectors((self.angle, self.speed), gravity)

As you can see, there's no reason to give up on Python 3 just because of this syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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