繁体   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