Python-TypeError:未绑定方法 [英] Python - TypeError: unbound method

查看:282
本文介绍了Python-TypeError:未绑定方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以自从我尝试将代码重构到不同的文件以来,这个Python问题一直给我带来麻烦.我有一个名为object.py的文件,并且其中的相关代码是:

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)

尝试调用此代码是:

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'

那么这一切到底是怎么回事,我应该如何重构呢?我还假设拥有一个叫做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?

感谢您的帮助!

推荐答案

更新

您正在名为object.py的文件中定义Object.但是客户端引用了object_info.Object.这是错字吗?

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

我还假设拥有一个叫做Object的类不是很好的编码习惯,对吗?

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

正确.将您的班级重命名为其他名称,例如GenericObjectGenericBase.也不要使用模块名称object.py.适当更改.

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

您正在构造Object的实例,但是操作方式是错误的.试试这个:

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)

Dive Into Python中的这个应该很有用.

This chapter from Dive Into Python should prove useful.

这篇关于Python-TypeError:未绑定方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆