【问题标题】:Clone and Expando class object in Python for App Engine在 Python for App Engine 中克隆和 Expando 类对象
【发布时间】:2011-05-04 06:13:48
【问题描述】:

在 Google App Engine 上使用 Python 时,克隆(制作副本)Expando 类对象的好方法是什么?

我在这里遇到了一些代码,但除非我弄错了,否则它不适用于 expando 属性:Copy an entity in Google App Engine datastore in Python without knowing property names at 'compile' time

谢谢!

【问题讨论】:

    标签: python google-app-engine expando


    【解决方案1】:

    这是包含动态属性的Nick's function 的修订版:

    def clone_entity(e, **extra_args):
      """Clones an entity, adding or overriding constructor attributes.
    
      The cloned entity will have exactly the same property values as the original
      entity, except where overridden. By default it will have no parent entity or
      key name, unless supplied.
    
      Args:
        e: The entity to clone
        extra_args: Keyword arguments to override from the cloned entity and pass
          to the constructor.
      Returns:
        A cloned, possibly modified, copy of entity e.
      """
      klass = e.__class__
      props = dict((k, v.__get__(e, klass)) for k, v in klass.properties().iteritems())
      props.update(dict([(k, getattr(e, k)) for k in e.dynamic_properties()]))
      props.update(extra_args)
      return klass(**props)
    

    【讨论】:

    • 应该是“e.dynamic_properties()”而不是“klass.dynamic_properties()”吗?
    • 另外,看起来 dynamic_properties() 返回一个列表而不是一个字典,所以“iteritems()”不起作用?
    • 谢谢,你在这两个方面都是对的。代码已相应更新。
    • 嘿,Drew,']' 之前应该有一个额外的 ')' 吗?: props.update(dict([(k, getattr(e, k) for k in e.dynamic_properties() )]))
    • 糟糕,这就是我没有测试它的结果。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2012-05-06
    • 1970-01-01
    相关资源
    最近更新 更多