类字典? [英] Dictionary with classes?

查看:98
本文介绍了类字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,是否可以通过字典实例化一个类?

  shapes = {'1':Square ,'2':Circle(),'3':Triangle()} 

x = shapes [raw_input()]


我想让用户从菜单中选择,而不是输入巨大的if else语句。例如,如果用户输入2,x将是Circle的新实例。这是可能吗?

解决方案

几乎。您想要的是

  shapes = {'1':Square,'2':Circle,'3':Triangle}只是在dict中的类名

x = shapes [raw_input()]()#get类从dict,然后调用它来创建一个形状实例。


In Python is it possible to instantiate a class through a dictionary?

shapes = {'1':Square(), '2':Circle(), '3':Triangle()}

x = shapes[raw_input()]

I want to let the user pick from a menu and not code huge if else statements on the input. For example if the user entered 2, x would then be a new instance of Circle. Is this possible?

解决方案

Almost. What you want is

shapes = {'1':Square, '2':Circle, '3':Triangle} # just the class names in the dict

x = shapes[raw_input()]() # get class from dict, then call it to create a shape instance.

这篇关于类字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆