Python - TypeError:未绑定方法

Bra*_*rad 5 python initialization attributeerror

所以这个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
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试专门编译此文件时,我收到此错误:

TypeError: unbound method __init__() must be called with Object instance as first argument (got int instance instead)
Run Code Online (Sandbox Code Playgroud)

试图调用它的代码是:

player = object_info.Object.__init__(BurglaryConstants.SCREEN_WIDTH/2, BurglaryConstants.SCREEN_HEIGHT/2, '@', libtcod.white)
Run Code Online (Sandbox Code Playgroud)

编译时会导致此错误:

AttributeError: 'module' object has no attribute 'Object'
Run Code Online (Sandbox Code Playgroud)

那么这一切究竟发生了什么呢?我该如何重构呢?另外我假设有一个名为Object的类不是一个非常好的编码实践,对吗?

谢谢你的帮助!

Man*_*dan 4

更新

您正在Object一个名为 的文件中进行定义object.py。然而客户提到object_info.Object。这是拼写错误吗?

另外,我认为拥有一个名为 Object 的类并不是一个很好的编码实践,对吗?

正确的。将您的类重命名为其他名称,例如GenericObjectGenericBase。也不要使用模块名称object.py。适当改变一下。

您正在构建一个实例,Object但您的做法是错误的。尝试这个:

player = object_info.Object(BurglaryConstants.SCREEN_WIDTH/2, BurglaryConstants.SCREEN_HEIGHT/2, '@', libtcod.white)
Run Code Online (Sandbox Code Playgroud)

深入 Python 中的这一章应该会很有用。