【问题标题】:Can a dictionary be passed directly to instantiate another object in python可以直接传递字典来实例化python中的另一个对象吗
【发布时间】:2014-09-14 19:12:12
【问题描述】:

我正在尝试将 parse.com 作为我的 django 应用程序的数据库。我已经安装了 parse_rest。

我有一个字典列表,每个字典的形式为:

all_practices = {'a':value1, 'b':value2 ...}

根据 Michael Otte 提供的答案,Add and save objects to parse.com db from django

我可以通过以下方式保存这个对象:

from parse_rest.datatypes import Object
class Profile(Object):
    pass

# instantiate with parameters
profile = Profile(name='Johnny', age=27)

有没有办法直接将字典对象作为profile对象的参数传递,从而得到:

profile = Profile(a='value1', b='value2')

【问题讨论】:

    标签: python django dictionary


    【解决方案1】:

    是的,使用keyword/dictionary unpacking operator **

    profile = Profile(**all_practices)
    

    【讨论】:

    • 基本上这是如何使用 *args 和 **kwargs - 有大量的概念参考,更完整的描述它是如何工作的谷歌这些术语。
    • 谢谢,这很容易! - 比尔
    猜你喜欢
    • 2011-06-02
    • 2018-01-21
    • 2023-01-17
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多