近期对PYTHON 动态创建类或修改父类的方法进行了学习,总结记录一下:
def createClass(cls):
class CustomizedClass(cls):
.......
return CustomizedClass
ClassList = createClass(list)
此方法比较容易理解,向函数传入父类即可
def create_read_thread(obj):
'''type完全动态构建类'''
def __init__fn(self, name=None):
obj.__init__(self)
self.__dict__['name'] = name
self.start()
def run(self):
print(self.name)
_name = 'QThread' if obj is QThread else 'Thread'
return type(f'Synt_Read_{_name}', (obj, ), {
'__init__': __init__fn,
'run': run,
})
Synt_Thread_read = create_read_thread(Thread)
Synt_QThread_read = create_read_thread(QThread)
利用type动态构建,定义类方法、类属性后,动态生成,比较繁琐。
def get_read_class(obj: object) -> object:
'''type 动态混入继承,实质是调整bases'''
_name = 'QThread' if obj is QThread else 'Thread'
ocl = type(f'Synt_Read_{_name}', (_read_class_meta, obj), {})
return ocl
ReqSynthesizer_Thread_read = get_read_class(Thread)
ReqSynthesizer_QThread_read = get_read_class(QThread)
class _read_class_meta:
def __init__(self, name=None):
super().__init__()
self._name = name
self.start()
def run(self):
print(self.name)
class ReqSynthesizer_Thread_read(_read_class_meta, Thread):
pass
class ReqSynthesizer_QThread_read(_read_class_meta, QThread):
pass
方法4也比较简单、明了。
本人更为推荐方法1和方法4,但灵活度差一些。
特此记录!