
[英]Python: How to use an object name to call the object itself and also as a string
[英]How to use a string' value as an object name
我正在尝试做这样的事情:
user_id = 12345
"user_id" = user("...") # "user" is my class
# I want to replace "user_id" with "12345"
可能吗?
如果你真的需要这个,你最好用dict:
my_objs = {}
user_id = 12345
my_objs[user_id] = User()
print(my_objs)
然后输出将是:
{12345: <__main__.User object at 0x123456789abc>}
您始终可以使用以下任一方法获取对象:
another_id = 12345
my_objs[another_id]
my_objs[12345]
如果你真的,真的需要这个,但不能使用dict, getattr
和setattr
可能会有所帮助:
user_name = "hahaha"
setattr(__import__(__name__), user_name, User())
print(hahaha)
new_name = "hahaha"
assert hahaha is getattr(__import__(__name__), new_name)
这将产生相同的输出,断言将通过。
注意这个方法在函数内部不能很好地工作,它只在模块级别上很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.