[英]ERROR: unbound method “method name” must be called with “Class Name” instance as first argument (got classobj instance instead)
I hope you guys can help me out here. 我希望你们能在这里帮助我。 I've been given this error from the following code: 下面的代码给了我这个错误:
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)
The code: 编码:
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
I'd really appreciate if someone could tell me what's going on here. 如果有人能告诉我这里发生了什么,我将非常感谢。 I started learning python 2.7 about 2 months ago. 我大约2个月前开始学习python 2.7。 Thanks! 谢谢!
The problem is that addBandit
requires an instance of BanditGroup
to be used. 问题是, addBandit
需要的实例BanditGroup
使用。 Adding (...)
after the class name will create one: 在类名后面添加(...)
将创建一个:
bg = BanditGroup(...)
Right now, you have bg
pointing to the class itself , not an instance of it. 现在,您有bg
指向类本身 ,而不是它的实例。
The same thing needs to be done here with Bandit
: 在Bandit
需要完成相同的操作:
b = Bandit(...)
Note: ...
means to pass in the appropriate arguments. 注意: ...
表示传递适当的参数。 You made BanditGroup.__init__
with a required a
parameter and Bandit.__init__
with required power
and life
parameters. 您为BanditGroup.__init__
设置了必需a
参数,并为Bandit.__init__
了必需的power
和life
参数。 Since I don't know what you want these to be, I left them out. 由于我不知道您想要这些是什么,因此我将其排除在外。
Try changing your code to (notice the parenthesis around class instantiation): 尝试将代码更改为(注意类实例化的括号):
while i <= howmanygroups:
bg = BanditGroup(a)
howmanybandits = random.randint(1,11)
while j <= howmanybandits:
b = Bandit(power, life)
bg.addBandit(b) #<-- line 60
Yes probably need parens when you create an instance of your Bandit and BanditGroup classes. 是的,当您创建Bandit和BanditGroup类的实例时,可能需要parens。 Otherwise, you're assigning a class to your variables, not an instance of a class. 否则,您将为变量分配一个类,而不是一个类的实例。
EG: bg = BanditGroup() EG:bg = BanditGroup()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.