python - 将代码从 Py3.0 转换为 2.7Py Super() 并打印语句

标签 python class

所以我从 redblob games 的这个好人那里得到了这段代码 ( http://www.redblobgames.com/ ),但我在将他的 Py3.0 代码转换为 Py2.7 时遇到了一些困难。

代码可以在这里找到。它很大,所以如果你不想看它,我会明白:( http://www.redblobgames.com/pathfinding/a-star/implementation.py )

如果您可以请建议我可以对其进行一些更改,我将不胜感激。目前我发现了 3 个错误,其中 2 个是我不太理解的语法。

<小时/>

语法1

def from_id_width(id, *, width):

错误是“*,”

<小时/>

语法2

print("%%-%ds" % width % draw_tile(graph, (x, y), style, width), end="")

错误是end=""

<小时/>

输入错误

class GridWithWeights(SquareGrid):
def __init__(self, width, height):
    super().__init__(width, height)
    self.weights = {}

super() 至少接受 1 个参数(给定 0 个)

但是当我将 GridWithWeights 放入 super() 中时:

TypeError: must be type, not classobj

最佳答案

要使 from_id_width 正常工作,您需要删除关键字参数标记 *:

def from_id_width(id, width):
   return (id % width, id // width)

print 可以通过从 __future__ 导入来修复:

from __future__ import print_function

最后__init__需要以不同的方式调用super:

class GridWithWeights(SquareGrid):
    def __init__(self, width, height):
        super(GridWithWeights, self).__init__(width, height)
        self.weights = {}

并且父类必须转换为新样式类:

class SquareGrid(object):

关于python - 将代码从 Py3.0 转换为 2.7Py Super() 并打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36150531/

相关文章:

jQuery:从类中获取 ID

python - 无法通过 Python 的 Selenium 定位按钮

python - 将嵌套字典转换为列表

python - 当数字为0时,如何在python中显示四舍五入的数字?

python - 错误是 : No module named postgresql. base

python - 在类和函数内外工作

java - (Android Studio) (Java) 使用 A 类中的 ArrayList 在 B 类中构建的方法时遇到问题

python - SQLAlchemy 支持 H2DB 吗?

java - 重用另一个类中的字段

C++ : Accessing private member of base or global variable from a derived class