首页 > 解决方案 > 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))


标签: pythonpython-3.x

解决方案


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.


推荐阅读