我希望你们能帮我。以下代码给了我这个错误:
Traceback (most recent call last):
File "C:Python27LibidlelibTarea5.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
如果有人能告诉我这里发生了什么,我将不胜感激。大约两个月前,我开始学习python 2.7。谢谢
尝试将代码更改为(注意类实例化周围的括号):
while i <= howmanygroups:
bg = BanditGroup(a)
howmanybandits = random.randint(1,11)
while j <= howmanybandits:
b = Bandit(power, life)
bg.addBandit(b) #<-- line 60
问题是addBandit
需要使用BanditGroup
的实例。在类名后添加(...)
将创建一个:
bg = BanditGroup(...)
现在,bg
指向类本身,而不是它的实例。
Bandit
:也需要做同样的事情
b = Bandit(...)
注意:...
表示传入适当的参数。您使用所需a
参数制作了BanditGroup.__init__
,使用所需的power
和life
参数制作了Bandit.__init__
。既然我不知道你想要这些是什么,我就把它们排除在外了。
Yes在创建Bandit和BanditGroup类的实例时可能需要parens。否则,您将为变量分配一个类,而不是一个类的实例。
EG:bg=BanditGroup()