views:

23

answers:

2

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  A: 

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.

Manoj Govindan
This didn't quite work, I still got the same AttributeError when compiling.
Brad
@Brad: Can you paste the stack trace of the error you got?
Manoj Govindan
@Brad: updated answer. See above.
Manoj Govindan
@Manoj - I actually imported object as object_info so that wasn't the problem.However I realized I was importing the file that calls object.py in the object.py file, which I assume is a big no no, as removing it caused the error to no longer occur.
Brad
+1  A: 

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).

delnan