القاموس مع الطبقات؟
-
05-07-2019 - |
سؤال
في بيثون أنه من الممكن إنشاء مثيل فئة من خلال القاموس؟
shapes = {'1':Square(), '2':Circle(), '3':Triangle()}
x = shapes[raw_input()]
وأريد أن ترك اختيار المستخدم من القائمة وليس رمز ضخمة إذا كانت تصريحات شيء آخر على المدخلات. على سبيل المثال إذا قام المستخدم بإدخال 2، فإن س ثم يكون مثيل جديد من الدائرة. هل هذا ممكن؟
المحلول
وتقريبا. ما تريده هو
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.
نصائح أخرى
وأنصح ظيفة المختار:
def choose(optiondict, prompt='Choose one:'):
print prompt
while 1:
for key, value in sorted(optiondict.items()):
print '%s) %s' % (key, value)
result = raw_input() # maybe with .lower()
if result in optiondict:
return optiondict[result]
print 'Not an option'
result = choose({'1': Square, '2': Circle, '3': Triangle})()
لا تنتمي إلى StackOverflow