PYTHON 動態建立類或修改父類的方法

2021-10-08 11:36:26 字數 1511 閱讀 8150

近期對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_', (obj, ), )

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_', (_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,但靈活度差一些。

特此記錄!

python建立例項屬性 建立新的類或例項屬性

問題 你想建立乙個新的擁有一些額外功能的例項屬性型別,比如型別檢查。解決方案 如果你想建立乙個全新的例項屬性,可以通過乙個描述器類的形式來定義它的功能。下面是乙個例子 descriptor attribute for an integer type checked attribute class i...

python 動態建立乙個類

class animal def eat self print eat class dog animal pass wangcai dog wangcai.eat 輸出 eat cat type cat animal,xiaohuamao cat xiaohuamao.eat 輸出 eat 元類就是...

Python中type()詳解 動態建立類

眾所周知 type 函式可以檢視變數的型別 先看乙個簡單的列子來看一下type檢視變數型別 class animal pass a animal print type a print type animal 可以發現我定義的animal類本身的型別是 type 從 python 直譯器的角度來看,當...