由于我最近对信息安全和网络编程感兴趣,因此我决定通过Internet学习Python。我正在尝试编写一段代码,它允许用户存储所需数量的人员的Biodata(姓名,年龄和工作)。然后O/P将包括所有这些人的生物数据以及人数。作为Python新手,我无法识别错误。 谢谢 - 希德IndexError:列表分配索引超出范围(in __init__)
这里是我的代码:
#!/usr/bin/python
class Bio:
counts = 0
myBio = []
def __init__(self, name, age, job):
Bio.myBio[Bio.counts] = name
Bio.myBio[Bio.counts+1] = age
Bio.myBio[Bio.counts+2] = job
Bio.counts + 1
def display(self):
for myBio in range(0, Bio.counts):
print myBio
while 1:
name = raw_input("Enter your name: ")
age = int(raw_input("Enter your age: "))
job = raw_input("Enter your Job: ")
details = Bio(name, age, job)
details.display()
print "Detail Count %d" % Bio.myBio
anymore = raw_input("Anymore details ?: (y/n)")
if anymore == 'n':
break
这里是我的O/P的轨迹:
./bio.py
Enter your name: Sid
Enter your age: 21
Enter your Job: InfoSec
Traceback (most recent call last):
File "./bio.py", line 25, in <module>
details = Bio(name, age, job)
File "./bio.py", line 9, in __init__
Bio.myBio[Bio.counts] = name
IndexError: list assignment index out of range*
代码有很多问题。您应该阅读[Python教程](http://docs.python.org/tutorial/)以熟悉Python的基础知识。 – BrenBarn
对此使用列表并没有什么好的理由。如果您对另一个数据结构有一些绝望的需求,那么Plain属性或者'dict'会更合适。还要注意'count'和'myBio'是*类变量*,而不是*实例变量*,这可能不是你想要的。这意味着它们对于所有实例都是相同的。用'__init __()'代替它们。 –
您知道,当您在提问时键入标题时,您会看到类似问题的列表。在这种情况下,您的确切错误的问题列表是*长*,阅读*任何*这些问题将回答你的问题,并且也更快。下次尝试。 –