Skip to main content
 首页 » 编程设计

python 32 语法无效但在 python 2 中有效

2024年10月24日1098°冷暖

我是 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 上工作而没有任何其他问题。

请您参考如下方法:

Tuple Parameter Unpacking已在 Python 3 中删除。

您有两个选择:您可以像这样编写您的 __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 

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