python - What is the right way in python to instantiate an object based on the object name?
问题描述
Having trouble finding a pattern for this in python. I would like to instantiate an object based on its name. If I have a large number of objects that share the same interface, how can I dynamically create instances of the object based on runtime data (i.e. replace the wonky if/elif statements)? should I be doing this from the parent object function, a separate function or in the constructor? Keep in mind I will have a library of 30+ objects that all share the same interface, but I need to determine at runtime based on configuration data which object type I am working with.
class Person(object):
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def isEmployee(self):
return False
def create(type)
if type == 'Employee':
return Employee(self.name)
elif type == 'Customer':
return Customer(self.name)
else:
return self
class Customer(Person):
def isEmployee(self):
return False
class Employee(Person):
def isEmployee(self):
return True
people = [
{ 'name': 'John', 'type': 'Employee' },
{ 'name': 'Jane', 'type': 'Employee' },
{ 'name': 'Frank', 'type': 'Prospect' },
{ 'name': 'Joyce', 'type': 'Customer' }
]
for person in people:
p = Person(person['name']).create(person['type'])
status = "gets" if p.isEmployee() else "does not get"
print("{} {} paycheck".format(p.getName(), status))
解决方案
You could do it using a dictionary mapping:
type2class = {
'Employee': Employee,
'Customer': Customer,
}
for person in people:
cls = type2class.get(person['type'], Person)
p = cls(person['name'])
# do rest
Then you don't need the if/else check.
推荐阅读
- javascript - useState 没有更新 - nextjs
- python - 用阶乘替换列表中 3 的倍数的偶数
- amazon-web-services - 使用 pre-commit 钩子获取“E0000 模板需要是一个对象”。
- discord.js - discord.js 锁定命令引发错误,无法读取未定义的“拒绝”
- title - 如何使用 Altair 在多个图表上移动/对齐 X 轴标题?
- python - 省略第一个单词并删除属于另一个单词的单词
- php - 从 php 中的二维数组中查找缺失值并插入缺失的元素
- c# - 我该如何处理“'Program.D(int)':并非所有代码路径都返回一个值”
- ios - 从 Swift 二进制文件中删除文件名
- c# - 如果绑定属性具有特定值,如何用圆圈覆盖单元格的内容?