Python - 类型错误:未绑定的方法 [英] Python - TypeError: unbound method

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

问题描述

所以这个 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)

编译时出现这个错误:

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 - 类型错误:未绑定的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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