脑子 发表于 2023-10-20 11:15:19

动态创建class

目的: 自由选择继承的父类是哪个.
方法: 使用type()函数.

type can be used to dynamically create a class. First parameter is the class name, second are the classes to inherit from and third are the initial attributes.

示例:

class ParentA:
    def a(self):
      print('hi, A')

class ParentB:
    def b(self):
      print('hi, B')

obj = type(
      'Child_class', # class name
      (ParentA, ParentB), # parent classes
      {
            'info': lambda self: print('hi, child')
      }
)()

obj.a()
obj.b()
obj.info()


static/image/hrline/5.gif
https://stackoverflow.com/questions/57071752/python-inheritance-choose-parent-class-using-argument
页: [1]
查看完整版本: 动态创建class