2011-05-04 54 views

回答

2

这里是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) 
+0

它应该是 “e.dynamic_properties()” 而不是 “klass.dynamic_properties()”? – 2011-05-04 13:22:32

+1

此外,它看起来像dynamic_properties()返回一个列表,而不是一个字典,所以“iteritems()”将无法正常工作? – 2011-05-04 13:27:26

+0

谢谢,你说的都对。代码已经相应更新。 – 2011-05-04 13:57:42