Python如何通过用户输入创建对应名称的类实例,需用字典实现吗?
问题根因
- 你代码里的
name变量先存储了用户输入的用户名字符串,后续又被重新赋值为Profile类的实例,原本输入的用户名直接被覆盖丢失 - 直接用用户输入的内容作为全局变量名风险极高,也不符合Python的常规开发规范,这也是你调用
test()时报变量未定义错误的原因:程序根本没有生成名为test的全局变量 - 额外小问题:输入提示的身高体重对应逻辑写反了,且input获取的内容默认是字符串类型,建议转为int/float后再存入实例属性
用字典实现的方案
用字典存储实例是完全符合需求的最优解法,字典的key存用户名,value存对应用户的Profile实例即可,实现代码如下:
class Profile(): def __init__(self, weight, height): self.weight = weight self.height = height # 全局字典存储所有用户的Profile实例 profiles = {} def create_object(): name = input("What's your name?").strip() # 修正了输入提示的对应关系,输入值转为int类型,需要支持小数可换为float new_height = int(input("What's your height?").strip()) new_weight = int(input("What's your weight?").strip()) # 将生成的实例存入字典 profiles[name] = Profile(new_weight, new_height) return profiles[name]
使用示例
>>> create_object() What's your name? test What's your height? 180 What's your weight? 70 <__main__.Profile object at 0x000002564D7CFE80> # 直接通过用户名从字典中读取对应实例即可 >>> profiles['test'].height 180 >>> profiles['test'].weight 70
如果需要批量创建10个实例,循环调用create_object()10次即可,所有实例都会自动存入profiles字典,不需要手动定义10个变量存储。
内容的提问来源于stack exchange,提问作者Dashy
相关产品推荐
相关产品推荐

