首页 > 解决方案 > 如何使用动态基类初始化实例

问题描述

环境:python3

我想要一些带有我的自定义方法和属性的通用对象,所以我创建了一个函数,它在内部从给定基类的类创建一个类和实例,如下所示。

但我不确定如何使用给定值初始化实例。如果您有任何想法,我将不胜感激?

def get_object_with_uuid(value):
    base = type(value)

    class ObjectAndUUID(base):
        def __init__(self):
            self.uuid = "dummy"
            super().__init__()

    return ObjectAndUUID()

if __name__ == '__main__':
    a = get_object_with_uuid([4,5,6])
    b = get_object_with_uuid((7,8,9))
    c = get_object_with_uuid(10)
    d = get_object_with_uuid("some_string")

    a.append(7)
    print(a)      # '[7]' -> I want this to be [4,5,6,7]
    print(a.uuid) # 'dummy' -> this is expected

    print(b)      # '()' -> I want this to be (7,8,9)
    print(b.uuid) # 'dummy' -> this is expected

    print(c)  # '0' -> I want this to be 10
    print(c.uuid)  # 'dummy' -> this is expected

    print(d)  # '' -> I want this to be 'some_string'
    print(d.uuid)  # 'dummy' -> this is expected
    # and so on...

标签: python-3.x

解决方案


据我所知,Python 没有通用类型的语法,基于当前的代码视图,没有必要继承strlistdictObkjectAndUUID. 我保留它只是为了保持一致性。

将参数传递给实例是通过__init__. 请注意, init 的参数之一是self,因此无需创建它。

def get_object_with_uuid(value):
    base = type(value)

    class ObjectAndUUID(base):
        def __init__(self, val):
            self.uuid = "dummy"
            self.val = val

    return ObjectAndUUID(value)

推荐阅读