2011-05-04 28 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