Skip to main content
 首页 » 编程设计

python之Python中如何根据属性选择子类

2025年05月04日13lautakyan007

对于一个 Django 项目,我有一个父类和几个子类。
在 Django 管理后端中,我希望能够选择正确的子类并使用其属性和方法。

这是我的想法:

class Parent: 
    _name = "parent" 
 
class Child1(Parent): 
    _name = "child 1" 
 
class Child2(Parent): 
    _name = "child 2" 

在管理员中,用户应该能够从下拉列表中选择“ child 1”或“ child 2”。

稍后在 API 中,应根据属性名称选择子类。

当然我可以只创建一个包含类名和属性名的字典,然后使用大量的 if 和 elif 语句,但那不会正确的做法。

我该如何解决这个问题,还是我的思考方向完全错误?

请您参考如下方法:

创建一个包含子类的字典,并将该属性作为键,然后始终像这样使用它:

class Parent: 
    _name = "parent" 
 
class Child1(Parent): 
    _name = "child 1" 
 
class Child2(Parent): 
    _name = "child 2" 
 
mydict = {'thisone': Child1, 'thatone': Child2} 
 
myinstance = mydict['thisone']() 

你甚至可以这样做:

mydict = {Child1._name: Child1,  
          Child2._name: Child2}