2017-03-27 77 views
1

添加类实例的数量不受限制用户输入我想使用如何在python

class reader 
def __init__(self, name, booksread) 
    self.name = name 
    self.booksread = booksread 
while True 
    option = input("Choose an option: ") 
    if option = 1: 
     #What to put here? 

我要创建的读取器类的实例的数量不受限制,但我只能找出如何通过使用该类的变量来进行有限的次数。我也需要稍后调用信息(而不会丢失它)。有没有可能在课堂上做到这一点?或者,我会用清单还是词典更好?

回答

0

第一个:if option == 1:在python 3中总是为false,输入只读取那里的字符串。
第二:python lists可以扩展,直到你用完RAM。
因此,解决办法是在周围的代码创建一个列表,并调用追加上,每一次你有一个新项目:

mylist = [] 
while True: 
    mylist.append(1) 
0

这是完全有可能来填充数据结构(如列表或字典)用给定的代码示例中,一个类的实例,你可以把实例放入一个列表:

class reader 
def __init__(self, name, booksread) 
    self.name = name 
    self.booksread = booksread 

list = [] 
while True: 
    option = input("Choose an option: ") 
    if option == 1: 
     list.append(reader(name,booksread)) 

注:我不知道你是如何获得的“名”或“booksread”的值,因此它们在list.append()行中的值只是占位符

要访问该列表中的实例,可以遍历它,或通过其索引访问元素,例如

# access each element of the list and print the name 
for reader in list: 
    print(reader.name) 

#print the name of the first element of the list 
print(list[0].name) 
+0

太棒了!这是一个很大的帮助。 – bruzanHD