首页 > 解决方案 > 更新属性并返回同一类的新副本

问题描述

class Main(object):

    def __init__(self,  config):
        selt.attributes = config

    def return_new_copy(self, additional_attributes):
        addtional_attributes.update(self.attributes)
        return Main(additional_attributes) 

我想更新实例属性并返回同一类的新实例。我想我想知道上面的代码是 Pythonic 还是肮脏的方法。由于这里没有提到的几个原因,我不能使用 classmethod。是否有另一种推荐的方法。

标签: python

解决方案


return_new_copy修改了传入的参数,这可能是不可取的。它还会在错误的方向上覆盖(优先于self.attributes

我会这样写:

def return_new_copy(self, additional_attributes):
     # python<3.5 if there are only string keys:
     #     attributes = dict(self.attributes, **additional_attributes)
     # python<3.5 if there are non-string keys:
     #     attributes = self.attributes.copy()
     #     attributes.update(additional_attributes)
     # python3.5+
     attributes = {**self.attributes, **additional_attributes}
     return type(self)(attributes)

一些细微之处: - 我确保复制输入属性和自身属性 - 我将附加属性合并到自身属性之上

如果您正在寻找自动执行此操作的内容,您可能需要查看namedtuple

例如:

>>> C = collections.namedtuple('C', ('a', 'b'))
>>> x = C(1, 2)
>>> x
C(a=1, b=2)
>>> y = x._replace(b=3)
>>> y
C(a=1, b=3)
>>> x
C(a=1, b=2)

推荐阅读