python 32语法无效,但在python 2中工作

时间:2016-03-09 12:11:27

标签: python python-3.x

我是python的新手,我目前面临的一个问题是,当游戏在python 3上运行时,它表示无效的语法错误,但是,它在python 2上没有任何问题。

你能否告诉我为什么在使用python3时会出现无效的语法错误?

class Ammo(pygame.sprite.Sprite):
    def __init__(self, color, (width, height)):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.speed = 0
        self.vector = 0

我在第

行收到SyntaxError
def __init__(self, color, (width, height)):

我想让上面的代码在python 3上运行,没有任何其他问题和问题。

2 个答案:

答案 0 :(得分:1)

Python 3中已删除

Tuple Parameter Unpacking

您有两种选择:您可以像这样编写__init__方法:

>>> class Foo(object):
...     def __init__(self, color, width, height):
...         print(color, width, height)

并通过提供三个参数或通过将元组的宽度和高度值解压缩来初始化对象:

>>> wh = (1, 0)
>>> Foo('blue', *wh)
blue 1 0

或者,如果您希望__init__从用户那里获取两个参数:

>>> class Foo(object):
...     def __init__(self, color, width_and_height):
...         width, height = width_and_height
...         print(color, width, height)

初始化如下所示:

>>> Foo('blue', wh)
blue 1 0

我更喜欢第一种解决方案。

答案 1 :(得分:1)

Python3中不再支持元组参数:http://www.python.org/dev/peps/pep-3113/

您可以在功能开头打开元组:

def add_vectors(v1, v2):
    angle_1, l_1 = v1
    angle_2, l_2 = v2
    x=math.sin(angle1)*l_1+math.sin(angle2)*l_2
    y=math.cos(angle1)*l_1+math.cos(angle2)*l_2

    angle=0.5*math.pi-math.atan2(y, x)
    length=math.hypot(x, y)
    return (angle, length)