【问题标题】:AttributeError: object has no attribute Python ErrorAttributeError:对象没有属性 Python 错误
【发布时间】:2023-03-22 14:16:01
【问题描述】:

我有这段代码,但它不能正常工作。

要点

class Point:
    I = 0
    J = 1

    def __init__(self, i: int, j: int):
        self._coordinate = [i, j]  # list

    # ..other code (getter and setter)

    def __key(self):
        return self.get_i(), self.get_j()

    def __eq__(self, other):
        if isinstance(other, Point):
            return self.__key() == other.__key()
        return NotImplemented

    def __hash__(self):
        return hash(self.__key())

PointType

class PointType(Point):

    def __init__(self, i: int, j: int, t: int):
        Point.__init__(self, i, j)
        self.__t = t

    # getters and setters

炸弹:

class Bomb(Thread, PointType):

    def __init__(self, i: int, j: int):
        Thread.__init__(self)
        PointType.__init__(self, i, j, BOMB)

    def run(self) -> None:
        # code

当我启动 Bomb Thread 时,这个程序给了我这个错误:AttributeError: 'Bomb' object has no attribute '_coordinate' 我认为错误是 hash。

完整的堆栈跟踪:

Traceback(最近一次调用最后一次):文件 “D:\Mario\Documents\BomberFriends\application\model\games.py”,行 第634章 植物()文件“D:\Mario\Documents\BomberFriends\application\model\games.py”,行 589,厂内 gameInstance.plantBomb(i, j) 文件“D:\Mario\Documents\BomberFriends\application\model\games.py”,行 151、植物炸弹 Bomb(i, j).start() 文件“D:\Mario\Documents\BomberFriends\application\model\games.py”,行 238,在 初始化 Thread.init(self) 文件 "C:\Users\Mario\AppData\Local\Programs\Python\Python39\lib\threading.py", 第 822 行,在 init 中 _dangling.add(self) 文件 "C:\Users\Mario\AppData\Local\Programs\Python\Python39\lib_weakrefset.py", 第 85 行,添加 self.data.add(ref(item, self._remove)) 文件“D:\Mario\Documents\BomberFriends\application\model\games.py”,行 97,在散列中 return hash(self.__key()) 文件“D:\Mario\Documents\BomberFriends\application\model\games.py”,行 89,在 __key 返回 self.get_i(), self.get_j() 文件“D:\Mario\Documents\BomberFriends\application\model\games.py”,行 69、在get_i中 return self._coordinate[Point.I] AttributeError: 'Bomb' object has no attribute '_coordinate'

我该如何解决?

【问题讨论】:

  • 请发布完整的堆栈跟踪和生成它的代码,这将提高答案的质量
  • @MichaelRuth 我已经更新了包括完整堆栈跟踪在内的最佳答案

标签: python python-3.x runtime-error hashcode attributeerror


【解决方案1】:

问题是由Bomb 中父初始化程序的顺序引起的。颠倒顺序消除错误:

class Bomb(Thread, PointType):
    def __init__(self, i: int, j: int):
        PointType.__init__(self, i, j, Bomb)
        Thread.__init__(self)

【讨论】:

    猜你喜欢
    • 2014-04-03
    • 2023-03-05
    • 2011-06-19
    • 2020-09-28
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多