gpt4 book ai didi

Python - 类型错误 : unbound method

转载 作者:太空狗 更新时间:2023-10-30 01:10:27 24 4
gpt4 key购买 nike

自从我尝试将代码重构到不同的文件中以来,这个 Python 问题一直困扰着我。我有一个名为 object.py 的文件,其中的相关代码是:

class Object:
#this is a generic object: the player, a monster, an item, the stairs...
#it's always represented by a character on screen.
def __init__(self, x, y, char, color):
self.x = x
self.y = y
self.char = char
self.color = color

def move(self, dx, dy):
#move by the given amount, if the destination is not blocked
#if not map[self.x + dx][self.y + dy].blocked:
self.x += dx
self.y += dy

现在,当我尝试专门编译这个文件时,我得到了这个错误:

TypeError: unbound method __init__() must be called with Object instance as first argument (got int instance instead)

试图调用它的代码是:

player = object_info.Object.__init__(BurglaryConstants.SCREEN_WIDTH/2, BurglaryConstants.SCREEN_HEIGHT/2, '@', libtcod.white)

编译时导致此错误的原因:

AttributeError: 'module' object has no attribute 'Object'

那么这一切到底是怎么回事,我应该如何重构它?此外,我认为拥有一个名为 Object 的类并不是一个很好的编码习惯,对吗?

感谢您的帮助!

最佳答案

更新

您正在一个名为 object.py 的文件中定义 Object。然而客户端引用了 object_info.Object。这是错字吗?

Also I assume having a class called Object isn't a very good coding practice, correct?

正确。将您的类重命名为其他名称,比如 GenericObjectGenericBase。也不要使用模块名称 object.py。适本地改变它。

还有

您正在构建 Object 的实例,但您的操作方式是错误的。试试这个:

player = object_info.Object(BurglaryConstants.SCREEN_WIDTH/2, BurglaryConstants.SCREEN_HEIGHT/2, '@', libtcod.white)

chapter来自 Dive Into Python 的文章应该证明是有用的。

关于Python - 类型错误 : unbound method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3558937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com