【问题标题】:ERROR: unbound method "method name" must be called with "Class Name" instance as first argument (got classobj instance instead)错误:必须以“类名”实例作为第一个参数调用未绑定的方法“方法名”(取而代之的是 classobj 实例)
【发布时间】:2013-11-22 23:45:05
【问题描述】:

我希望你们能在这里帮助我。 我从以下代码中得到了这个错误:

Traceback (most recent call last):
  File "C:\Python27\Lib\idlelib\Tarea5.py", line 60, in <module>
    bg.addBandit(b)
TypeError: unbound method addBandit() must be called with BanditGroup instance as first argument (got classobj instance instead)

代码:

from numpy import *
from matplotlib import pyplot as p
class Bandit:
    power = random.uniform(15,46)
    life = random.uniform(40,81)
    def __init__(self, power, life):
        self.power = power
        self.life = life
class BanditGroup:
    def __init__(self,a):
        self.group = [a] #Where 'a' is an object of the class Bandit
    def addBandit(self,b):
        self.group.append(b) #Where 'b' is an object of the class Bandit
        return self.group

howmanygroups = random.randint(4,11)
i = 0
j = 0
while i <= howmanygroups:
    bg = BanditGroup
    howmanybandits = random.randint(1,11)
    while j <= howmanybandits:
        b = Bandit
        bg.addBandit(b) #<-- line 60
        j+=1
    bgposx = random.uniform(0,50000)
    bgposy = random.uniform(0,50000)
    p.plot(bgposx,bgposy,'r^')
    i+=1

如果有人能告诉我这里发生了什么,我将不胜感激。我大约 2 个月前开始学习 python 2.7。 谢谢!

【问题讨论】:

  • 你实际上并没有制作任何强盗或一群强盗来放置它们。BanditBanditGroup 是类;您的代码现在尝试做的类似于尝试坐在椅子的抽象概念上,而不是去宜家并找一把特定的椅子坐下。

标签: python class python-2.7 methods matplotlib


【解决方案1】:

尝试将您的代码更改为(注意类实例化周围的括号):

while i <= howmanygroups:
    bg = BanditGroup(a)
    howmanybandits = random.randint(1,11)
    while j <= howmanybandits:
        b = Bandit(power, life)
        bg.addBandit(b) #<-- line 60

【讨论】:

  • 不要忘记构造函数接受参数。
  • @user2357112 哦!没错 :) 一时冲动,我忘记了。
  • 是的!这是一个没有参数的构造函数!我删除了 BanditGroup 构造函数上请求的参数,所以现在它可以工作了!谢谢!
【解决方案2】:

问题在于addBandit 需要使用BanditGroup 的实例。在类名后添加(...)会创建一个:

bg = BanditGroup(...)

现在,您有 bg 指向类本身,而不是它的实例。

这里需要用Bandit做同样的事情:

b = Bandit(...)

注意:... 表示传入适当的参数。您使用必需的a 参数创建了BanditGroup.__init__,使用必需的powerlife 参数创建了Bandit.__init__。因为我不知道你想要这些是什么,所以我把它们排除在外了。

【讨论】:

  • 是的,就是这样......我的解决方案是删除 BanditGroup 的 def __init 上所需的元素 a。现在它完美地工作了!非常感谢!
【解决方案3】:

是的,当您创建 Bandit 和 BanditGroup 类的实例时,可能需要括号。否则,您将一个类分配给您的变量,而不是一个类的实例。

EG: bg = BanditGroup()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-07
    • 2018-05-10
    • 2013-12-31
    • 2011-05-27
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    相关资源
    最近更新 更多