python-3.x - 如何使用动态基类初始化实例
问题描述
环境: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 没有通用类型的语法,基于当前的代码视图,没有必要继承str
,list
或dict
在ObkjectAndUUID
. 我保留它只是为了保持一致性。
将参数传递给实例是通过__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)
推荐阅读
- php - 如何使用 AdSense API 向网站用户显示保存的报告?
- android - Android:如何为 EditText 指定 2 种样式?
- memory-management - 内存不足错误。如何定位?怎么解决?
- android - Uri 和 getData 在上传到 Firebase 期间为空对象
- sql-server - 真正的零安全比较
- ios - 在子视图控制器之间切换
- python - 找不到解决方法:恰好需要 1 个参数(给定 2 个)
- javascript - 如何保存文本框中的输入,然后移至下一页?(Javascript/HTML)
- javascript - 类型错误:这是未定义的;无法访问其“道具”属性
- windows - DynamoDb SocketException:尝试对无法访问的网络进行套接字操作