我有一个orc
对象和一个radar
对象,需要跟踪它所能看到的orc
。我使用列表跟踪orc
,但是当我试图从列表中拉出一个orc
(或关于它的数据)时,我得到了一个属性错误。你知道吗
确切的错误是:
AttributeError: type object 'orc' has no attribute 'name'
这是雷达课
from source.orc import orc
class radar(object):
"""
radar Class
"""
def __init__(self, maxOrcs=25):
self.maxOrcs = maxOrcs
self.numOrcs = 0
self.orcList = [orc]
logger.info('Radar created!')
def addOrc(self, orc=None):
self.numOrcs = self.numOrcs +1
self.orcList.append(orc)
logger.info('Orc added to battlefield!')
def distance(self, name):
retVal = None
logger.debug('calculating distance')
for orc in self.orcList:
if name in orc.name:
retVal = ( (500 - orc.locx) + (500 - orc.locy) )
break
return retVal
如果有帮助的话这是兽人的职业
class orc(object): #Orc class
def __init__(self, name='Krusk', locx=1, locy=1, speed=1):
#set name
if(len(name) < 20):
self.name = name
else:
self.name = 'Krusk'
logger.warning('Default name used')
#set x coord
if(isinstance(locx, int) != True):
self.locx = 1
logger.warning('x coordinate set to 1, Not an int')
elif(locx < 1):
self.locx = 1
logger.warning('x coordinate set to 1, passed value to low')
elif(locx > 1000):
self.locx = 1000
logger.warning('x coordinate set to 1000, passed value to high')
else:
self.locx = locx
#set y coord
if(isinstance(locy, int) != True):
self.locy = 1
logger.warning('x coordinate set to 1, Not an int')
elif(locy < 1):
self.locy = 1
logger.warning('y coordinate set to 1, passed value to low')
elif(locy > 1000):
self.locy = 1000
logger.warning('x coordinate set to 1000, passed value to high')
else:
self.locy = locy
#set speed
if(speed < 0):
self.speed = 0
logger.warning('speed set to 0, passed value cannot be negative')
else:
self.speed = speed
logger.info('Orc created!')
您没有在此处创建
orc
类的实例:您在那里使用了类,而
orc
类没有name属性。或许您打算创建一个实例:您的代码还同时使用
orc
作为类名和局部变量(在循环中或作为函数参数),这增加了混淆的可能性。你知道吗您应该为类使用CamelCase命名来避免这种情况;请参见Python styleguide:
以及
而创建实例就变成了:
尽管
self.orc_list
会更好,但如果您仍然遵循样式指南的话。你知道吗我同意其他人的观点,这一行代码就是问题所在:
不过,我不同意他们的看法。我想你不想把任何东西放在你的初始值列表中。我想您应该创建一个空列表:
当您调用addOrc()添加条目时,它将准备好接受条目。这与在初始值设定项中将计数设置为0一致。最有意义的是,因为您的初始值设定项没有收到要添加到列表中的orc对象。你知道吗
编辑:
由于您是按名称从列表中检索,因此可以考虑使用按名称键控的dict作为存储,而不是列表。dict将允许您直接访问所需的orc,而不必遍历整个列表直到找到所需的。你知道吗
而不是:
相关问题 更多 >
编程相关推荐