因此,自从我尝试将代码重构为不同的文件以来,这个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的文件中定义object.py。但是客户端引用了object_info.Object。这是错字吗?



正确的。将您的类(class)重命名为GenericObjectGenericBase。也不要使用模块名称object.py。适当更改。



您正在构造Object的实例,但是您执行的方式是错误的。试试这个:

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

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

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

10-11 20:29
查看更多