Python - 类型错误:未绑定方法
这个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并不是一个好的编码习惯,对吧?
谢谢你的帮助!
2 个回答
1
首先,记得要使用新式类,也就是要从 object
这个类继承。如果你使用的是 Python 3,那就不用担心,因为 Python 3 只有新式类。
其次,这里调用 __init__
很可能是不对的。如果你想创建一个新的对象,只需要写 Object(x, y, char, color)
就可以了。
4
更新
你在一个叫做 object.py
的文件里定义了 Object
。但是客户端却提到 object_info.Object
。这是个打字错误吗?
我还想问,叫一个类为 Object 这样做是不是不太好呢?
没错。最好把你的类改个名字,比如叫 GenericObject
或者 GenericBase
。另外,文件名 object.py
也不要用,改成其他合适的名字。
另外
你在创建 Object
的实例时,做法是错的。试试这样:
player = object_info.Object(BurglaryConstants.SCREEN_WIDTH/2, BurglaryConstants.SCREEN_HEIGHT/2, '@', libtcod.white)
这篇来自 Dive Into Python 的章节应该会对你有帮助。