我正在尝试使用
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 :(得分:0)
首先:if option == 1:
在python 3中始终为false,输入只在那里读取字符串
第二:python lists可以扩展,直到RAM耗尽为止
所以解决方案是在周围的代码中创建一个列表,并在每次有新项目时调用append:
mylist = []
while True:
mylist.append(1)
答案 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))
注意:我不知道你是如何获得'name'或'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)