python - 如何制作一个根据键调用不同类的函数?
问题描述
我需要一个函数(def check)来创建一个类的实例并从该类中获取一个列表。
但是有很多类,传递的'key'参数是我想要创建一个实例的类的编号。
# if the 'key' passed is 1 then it should make an instance of Class1
# if the 'key' passed is 2 then it should make an instance of Class2
def check(self, key):
list1 = Class1().list1. # it should call Class1().list1 if the key is 1 and Class2.()list1 if the key is 2
list2 = Class1().list2
list3 = Class1().list3
那么如何使 check() 函数更改它创建实例的类?
我认为我不能做出 if 语句并根据键更改它调用的类,因为有很多类,并且为每个类制作“if”语句会非常重复。
这是课程:
class Class1:
def __init__(self):
self.quiz_name = 'Cities and Countries - part 1'
self.list1 = []
self.list2 = [] # the three lists
self.list3 = []
self.list1.append('Select the European City: ')
self.list2.extend(['Abu Dhabi', 'Washington DC', 'New York', 'Rome'])
self.list3.append(4)
...
class Class2:
def __init__(self):
self.quiz_name = 'Cities and Countries - part 1' # the data in the lists here are different by each class, but I'm just giving an example of the classes
self.list1 = []
self.list2 = []
self.list3 = []
self.list1.append('Select the European City: ')
self.list2.extend(['Abu Dhabi', 'Washington DC', 'New York', 'Rome'])
self.list3.append(4)
...
# there are more classes
解决方案
要回答您的具体问题,除非我遗漏了一些明显的东西,否则一种方法是创建一个字典,将键映射到类:
def check(self, key):
the_list = {
1: Class1,
2: Class2,
3: Class3
}[key]().list1
但是,我真正的建议是重构您的代码。您的课程(名称不佳,Class1
并且Class2
是糟糕的,非描述性的课程名称)似乎唯一的目的是创建不同的测验。但是,测验的功能或界面并没有什么不同——它们只是内容不同。我会说这些是不适合上课的候选人-我认为您不能证明为每个测验单独开设课程是合理的。
一个Quiz
班级会更合适。事实上,你甚至可能根本不需要上课。除非您没有显示更多代码,否则您可以将测验存储在某种集合中。这里不需要遵循严格的模式,但让我们做一些合理的 JSON-y 操作:
quizzes = [
{
"name": " Cities and Countries - part 1",
"questions": [
{
"title": "Select the European City: ",
"answers": [
"Abu Dhabi",
"Washington DC",
"New York",
"Rome"
],
"correct_answer": "Rome"
}
]
}
]
推荐阅读
- django - 是否可以使用 django orm 按字段名分组?
- javascript - ESLint 问题:标准指南,还是流行的风格指南
- typescript - 如何使 TypeScript 从数组中推断参数的数量和类型
- node.js - 无头木偶截图不渲染 WebGL 画布
- list - 在 Powershell 中,如何对 DirectoryInfo 的 Collections.Generic.List 进行排序?
- rust - 约束 Rust 方法以接受有效类型对的两个变量
- kubernetes - 批量删除 Kubernetes PVC ebs 卷
- weblogic12c - java.lang.LinkageError:加载程序约束违规:
- android - 如何全屏显示照片?
- regex - 正则表达式仅替换组