python - 更新属性并返回同一类的新副本
问题描述
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。是否有另一种推荐的方法。
解决方案
您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)
推荐阅读
- elasticsearch - Elasticsearch 如何确定要查询集群中的哪个节点
- java - 为什么在windows系统上找不到规范化路径的文件?
- teradata - Oracle 语法与 teradata 语法
- firebase - 通过 Fastlane 将 dSYMS 上传到 Firebase
- asp.net-web-api2 - 从外部使用 Windows 身份验证调用 C# Web API
- java - JavaFX - 在主方法中从另一个类事件打开场景
- powershell - 从内存中发送-MailMessage 附件
- ffmpeg - Ffmpeg 无法对 mp2.mxf 进行编码“无法在 BodySID 1 中找到 xxxxxx 的绝对偏移量 - 部分文件?”
- c# - 如何使用 WPF 应用程序将 id 添加到列表框条目以删除条目以及在列表中记录
- outlook-redemption - 使用 Redemption Safe* 对象对附件进行的修改不会反映在检查器中