【问题标题】:How to convert some code Python2 to Python3.x?如何将一些代码 Python2 转换为 Python3.x?
【发布时间】:2017-08-09 13:26:00
【问题描述】:

我在我的游戏中处理动画,但我遇到了一个错误..你能帮帮我吗?)

或者我需要添加我的所有代码吗?

class Animation:
    def __init__(self, x, y, sprites=None, time=100):
        self.x = x
        self.y = y
        self.sprites = sprites
        self.time = time
        self.work_time = 0
        self.skip_frame = 0
        self.frame = 0

    def update(self, dt):
        self.work_time += dt
        self.skip_frame = self.work_time // self.time
        if self.skip_frame > 0:
            self.work_time = self.work_time % self.time
            self.frame += self.skip_frame
            if self.frame >= len(self.sprites):
                self.frame = 0

    def get_sprite(self):
        return self.sprites[self.frame]

Traceback (most recent call last):
  File "C:\Users\Zyzz\Desktop\game\bin.py", line 210, in <module>
    target.update(dt)
  File "C:\Users\Zyzz\Desktop\game\bin.py", line 98, in update
    self.skip_frame = self.work_time // self.time
TypeError: unsupported operand type(s) for //: 'int' and 'module'

【问题讨论】:

  • 这与你如何调用Animation(..)构造函数有关。
  • 我需要更改构造函数的名称吗?
  • Noo... 这就是它们的名称。使用time 参数...
  • 不,您需要更改实例化它们的方式。当您创建 Animation 时,您传递的 time 是什么?那就是错误所抱怨的module,无论Python版本如何,它都会发生。当然,由于代码中其他地方的原因,Python 3 传递了一个 module,而 Python 2 传递了一个 int,这可能会发生。

标签: python python-3.x python-2.x code-conversion


【解决方案1】:

我在您的代码中可以看到它与 python2/python3 中的代码无关。

这里self.time = time,时间好像是导入的模块。
您正在尝试self.skip_frame = self.work_time // self.time,其中self.work_timedef __init__(...) 之前用0 初始化
它试图在 int(0) 和一个不可接受的模块(time) 之间进行操作。

但是根据您的问题标题,如果您希望代码从 python2.x 迁移到兼容 python3.x,则有一个可用的包2to3
你可以使用python-tools安装2to3

$ 2to3 example.py
$ 2to3 -w example.py # -w for write the changes back to file

【讨论】:

    猜你喜欢
    • 2021-07-10
    • 2017-01-24
    • 2020-10-11
    • 1970-01-01
    • 2018-03-09
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多