Python 如何在运行时创建对象并将其引用名称保存在列表中
我已经创建了一个名为“runtime”的类,我想在运行时创建这个类的几个实例Python 如何在运行时创建对象并将其引用名称保存在列表中,python,Python,我已经创建了一个名为“runtime”的类,我想在运行时创建这个类的几个实例 class runtime: products = [] number_of_objects = 0 max_objects = 10 def __init__(self, name): self.name = name print(self.name) runtime.number_of_objects += 1 def ge
class runtime:
products = []
number_of_objects = 0
max_objects = 10
def __init__(self, name):
self.name = name
print(self.name)
runtime.number_of_objects += 1
def get_name(self):
return self.name
@classmethod
def list_of_products(cls):
for i in cls.products:
print(i)
while (True):
print("1 create")
print("2 view")
print("3 delete")
operation = input("enter your choice:")
if int(operation) == 1:
nick_name = input("enter nickname of the product:")
runtime.products.append(nick_name)
nick_name = runtime(nick_name)
elif int(operation) == 2:
runtime.list_of_products()
runtime.products[0].get_name()
elif int(operation) == 3:
pass
else:
print("choice unknown")
但是,在查看操作过程中,当我尝试获取已创建实例的名称时,会出现以下错误:
Traceback (most recent call last):
File "runtime objects.py", line 34, in <module>
eval(runtime.products[0]).get_name()
File "<string>", line 1, in <module>
NameError: name 'object1' is not defined
回溯(最近一次呼叫最后一次):
文件“runtime objects.py”,第34行,在
eval(runtime.products[0]).get_name()
文件“”,第1行,在
NameError:未定义名称“object1”
当我省略eval()函数时,它返回AttributeError更改变量引用的对象不会更改它引用的前一个对象的值 所以当你在做:
nick\u name=input(“输入产品的昵称:”)
runtime.products.append(nick_name)
nick\u name=运行时(nick\u name)
您所要做的就是将一些字符串添加到runtime.products
列表中,然后使nick\u name
变量指向一个从未使用过的新runtime
对象
如果要创建运行时
对象的列表,只需替换行的顺序:
nick\u name=input(“输入产品的昵称:”)
nick\u name=运行时(nick\u name)
runtime.products.append(nick_name)
或者简单地说:
runtime.products.append(runtime(input("enter nickname of the product:")))
现在创建一个
运行时对象,然后将其添加到列表中。需要进行两次修改
第一。在创建操作上,修改追加的顺序
nick_name = input("enter nickname of the product:")
nick_name = runtime(nick_name)
runtime.products.append(nick_name)
第二。视图操作(int(operation)==2
)的意义是获取类的名称,因为这是添加要选择的类所必需的
为此添加:
number_product = input("enter number of the product:")
修改的类为:
class runtime:
products = []
number_of_objects = 0
max_objects = 10
def __init__(self, name):
self.name = name
print(self.name)
runtime.number_of_objects += 1
def get_name(self):
return self.name
@classmethod
def list_of_products(cls):
for j, i in enumerate(cls.products):
print(j, i)
while True:
print("1 create")
print("2 view")
print("3 delete")
operation = input("enter your choice:")
if int(operation) == 1:
nick_name = input("enter nickname of the product:")
nick_name = runtime(nick_name)
runtime.products.append(nick_name)
elif int(operation) == 2:
runtime.list_of_products()
number_product = input("enter number of the product:")
print(runtime.products[int(number_product)].get_name())
elif int(operation) == 3:
pass
else:
print("choice unknown")
在runtime.products.append(nick\u name)
中,nick\u name
是一个字符串,您需要首先创建一个实例:runtime(nick\u name)
。另外,你的代码和回溯来自不同的版本。谢谢,伙计,通过阅读你的评论,我试着换行了。当我第一次实例化对象,然后将其附加到列表中时,它可以正常工作:)