python怎么动态创建类?python动态类测试例子

发布时间:2020-06-05编辑:脚本学堂
有关python动态创建类的一段代码,包括python函数主体,测试样式与执行结果,python类的动态创建与测试实例,一起来学习下。

1、python程序主体    
 

复制代码 代码示例:
#author: D.Lucifer
def create_object(object_attribute):
    class o: pass
    if '#class' in object_attribute.keys():
        (module_name, class_name) = object_attribute['#class'].rsplit('.', 1)
        module_meta = __import__(module_name)
        class_meta = getattr(module_meta, class_name)
        o = class_meta()
    for k in object_attribute:
        if str(type(object_attribute[k])) == '<class 'dict'>':
            setattr(o, k, create_object(object_attribute[k]))
        else:
            setattr(o, k, object_attribute[k])
    return o

2、测试(example.py)    
 

复制代码 代码示例:
class class1:
    def __init__(self):
        pass
    def print1(self):
        print('studio_name:' + str(self.studio))
class class2:
    def __init__(self):
        pass
    def print2(self):
        print('room:' + str(self.room))

3、测试脚本    
 

复制代码 代码示例:
def test():
    dict_object = {"#class": "example.class1",
                   "studio": "demonstudio",
                   "office": {"#class": "example.class2",
                              "floor": 5,
                              "room": "501"
                              }
                   }
    o = create_object(dict_object)
    o.print1()
    o.office.print2()
    print(o.studio)
    print(o.office.floor)
test()

4、执行结果    
 

复制代码 代码示例:
>>>
studio_name:demonstudio
room:501
demonstudio
5
>>>