python 如何动态的创建class

class f1:
    def __init__(self):
        self.name = "f1"
    def printF1(self):
        print("this is f1")

class f2:
    def __init__(self):
        self.name = "f2"
    def printF2(self):
        print("this is f2")

class f3:
    def __init__(self):
        self.name = "f3"
    def printF1(self):
        print("this is f3")

# 根据参数动态的选择class所要继承的父类
input = "all"
if input == "f1":
    baseClass = (f1)
elif input == "f2":
    baseClass = (f2)
elif input == "f3":
    baseClass = (f3)
else:
    baseClass = (f1,f2,f3)

def __init__(self):
    self.fname = "fson"
    self.age = 10
    print("this is init")

def printDict(self):
    print(self.__dict__)

def printMRO(self):
    print(type(self).__mro__)
    print(type(self).__bases__)
# type(类的名称,继承的父类,类的函数)
fson = type("fson",baseClass,{"__init__":__init__,"printDict":printDict,"printMRO":printMRO})
fsonObject = fson()
fsonObject.printDict()
fsonObject.printMRO()

 

posted @ 2024-06-20 17:16  朵朵奇fa  阅读(12)  评论(0编辑  收藏  举报