【问题标题】:What would be the best way to have object properties also contain data source?让对象属性也包含数据源的最佳方法是什么?
【发布时间】:2022-01-25 23:32:45
【问题描述】:

我有一个项目,我将各种数据源混合到一个对象实例中。不同的属性来自不同的来源,但我想跟踪哪些数据来自哪里。该项目使用 Python,目前使用 Pydantic 来处理一些序列化。你会怎么做?有没有办法扩展 Pydantic 字段来处理这种情况?数据源将在运行时/对象实例化时已知,不一定是对象定义。

一般流程可能是这样的:

  1. 从源 A 创建稀疏对象(将所有对象属性归于源 A)
  2. 从源 B 创建另一个稀疏对象(将所有对象属性归于源 B)
  3. 使用属性保存到数据存储中

【问题讨论】:

    标签: python data-modeling pydantic


    【解决方案1】:

    在 Python 中,您可以在运行时将属性附加到对象。只需创建一个带有字典作为属性的商店对象,您可以在其中保存源代码,然后执行以下操作:

    class Store():
        def __init__(self):
            self.sources = {}
    
    
    # Some custom object A
    class ObjectA():
        def __init__(self):
            self.a_0 = 3
            self.a_1 = lambda t: str(t)
    
    # Some custom object B
    class ObjectB():
        def __init__(self):
            self.b_0 = dict(foo=3, bar=4)
            self.b_1 = set([7, 8])
           
    store = Store()
    obj_a = ObjectA()
    obj_b = ObjectB()
    
    for obj in (obj_a, obj_b):
        # Get all attributes except the special ones
        attributes = [t for t in dir(obj) if not t.startswith("__")]
        
        # Add them to the store as attributes and save their sources as
        # class name in store.sources
        for attr in attributes:
            setattr(store, attr, getattr(obj, attr))
            store.sources.update({attr: type(obj)})
    

    给你

    store.sources
    {'a_0': __main__.ObjectA,
     'a_1': __main__.ObjectA,
     'b_0': __main__.ObjectB,
     'b_1': __main__.ObjectB}
    

    你可以做到

    print(store.a_0)
    print(store.a_1)
    print(store.b_0)
    print(store.b_1)
    

    导致

    3
    <function ObjectA.__init__.<locals>.<lambda> at 0x000001837CDBE5E0>
    {'foo': 3, 'bar': 4}
    {8, 7}
    

    【讨论】:

    • 我非常感谢您通过示例进行深入回答!这与我发现自己的倾斜方式类似,只是一个不同的对象,其中包含设置属性集的此类元数据。谢谢!
    • @four43 不客气,儿子。那会回答您的问题还是您正在寻找其他东西?如果没有,请随时接受答案。
    • 我很想知道是否还有其他方法。我会确保在几天内标记答案。
    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 2020-08-12
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多