簡體   English   中英

使用type()創建子類時調用超類init

[英]calling super class init when child class is created using type()

我試圖使用python type()方法動態創建一個類。

所以,說我有一個基類'A'

>>> class A:
    def __init__(self):
        print("I am in init of A..")

現在我使用type方法創建一個子類'C'

>>> C = type('C',(A,),{})

當我創建一個對象

>>> c = C()
I am in init of A..

基類的init也被正確調用..

現在我想在我的init方法中做一些事情,然后我編寫一個自定義的init方法..

>>> def BsInit(self):
    print ("I am in init of B..")

我創建一個類'B'並創建一個實例..

>>> B = type('B',(A,),{'__init__':BsInit})
>>> b = B()
I am in init of B..

A類的初始化根本沒有被調用..

所以試着像這樣修改BsInit方法:

>>> def BsInit(self):
    super().__init__();
    print ("I am in init of B..")

當我創建一個實例時,我得到以下錯誤...

>>> B = type('B',(A,),{'__init__':BsInit})
>>> b = B()
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    b = B()
  File "<pyshell#19>", line 2, in BsInit
    super().__init__();print ("I am in init of B..")
RuntimeError: super(): __class__ cell not found

我用自定義init使用type()找到的所有例子都非常簡單,比如只是初始化一個變量..但如果我想調用基類Init也是如何做到的?

你需要像這樣調用它: super(B, self).__init__()

你需要在init方法而不是self中傳遞cls。 以下是您的問題的解決方案:

def init(cls):
    super(type(cls), cls).__init__()

B = type('B',(A,),{'__init__':init})
b = B()
"I am in init of A.."

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM