Python - TypeError: unbound method

拥有回忆 提交于 2020-01-02 04:47:07

问题


So this Python problem has been giving me problems since I've tried refactoring the code into different files. I have a file called object.py and in it, the related code is:

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

Now, when I try to compile this file specifically I get this error:

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

The code that is attempting to call this is:

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

Which causes this error when compiling:

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

So what the heck is going on with all this and how should I be refactoring this? Also I assume having a class called Object isn't a very good coding practice, correct?

Thanks for your help!


回答1:


Update

You are defining Object in a file called object.py. And yet the client refers to object_info.Object. Is this a typo?

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

Correct. Rename your class to something else, say GenericObject or GenericBase. Also don't use the module name object.py. Change it appropriately.

Also

You are constructing an instance of Object but the way you are doing it is wrong. Try this:

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

This chapter from Dive Into Python should prove useful.




回答2:


First, always use new-style classes, i.e. inherit from object. (This is not needed if you are running Python 3, which has only new-style classes)

Second, calling __init__ is very likely wrong here - if you want to instanciate a new Object, just write Object(x, y, char, color).



来源:https://stackoverflow.com/questions/3558937/python-typeerror-unbound-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!