簡體   English   中英

如何從超類實例創建子類實例

[英]How to create a subclass instance from a superclass instance

我想從Python中的超類實例創建一個子類實例。 假設我有這樣的事情:

class A():
    def __init__(self, type):
        ...
        self.type = type # this will be something that corresponds to either B or C

class B(A):
    def do_something():
        # this method is subclass specific

class C(A):
    def do_something():
        # this method is again subclass specific

我有一個函數接收A的實例,我需要根據A的屬性type創建一個B或C(或D ...)的實例。

我不知道該如何解決這個問題。 有沒有辦法解決這個問題,還是需要重新設計解決方案?

謝謝

使用從類型映射到類的字典。

class A():
    typemap = {}

    def __init__(self, typearg): # renamed this argument so it doesn't shadow standard type() function
        self.type = typearg
        self.typemap[typearg] = type(self)

    def create_child(self, *args):
        return typemap[self.type](*args)

構造函數運行時, type(self)獲取正在創建的對象的子類。 然后將其存儲在字典中,以便我們可以使用self.type查找它。

create_child()在字典中查找該類,並調用它來創建該子類的新實例。

首先重新定義A,B和C類,如下所示。 請注意,您還需要通過super().__init__()type值從子類傳遞到超類構造函數。

class A():
    def __init__(self, type):
        ...
        self.type = type # this will be something that corresponds to either B or C

class B:

    def __init__(self, type):
        super().__init__(type)

    def do_something(self):
        print('do_something called for B')

class C:

    def __init__(self, type):
        super().__init__(type)

    def do_something(self):
       print('do_something called for C')

然后創建另一個類,可以決定是否為您調用B和C,並在本地保存該對象

class User:

    def __init__(self, type):
        self.obj = None
        if type == 'B':
            self.obj = B(type)
        elif type == 'C':
            self.obj = C(type)

然后,您可以使用不同類型實例化用戶類,並查看是否調用了正確的do_something

user_B = User('B')
user_B.obj.do_something()
#do_something called for B
user_C = User('C')
user_C.obj.do_something()
#do_something called for C

暫無
暫無

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

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