我有一个大的字典。我想将每个键值对分配给一个类的属性。目前我在下面的代码段中有一些内容。它的作品,但它不漂亮。有一个更好的方法吗?从字典中分配属性值
伪蟒蛇片段:
config = A large dictionary
self.Width = config['width']
self.Height = config['height']
self.Text = config['text']
self.Font = config['font']
etc...
我有一个大的字典。我想将每个键值对分配给一个类的属性。目前我在下面的代码段中有一些内容。它的作品,但它不漂亮。有一个更好的方法吗?从字典中分配属性值
伪蟒蛇片段:
config = A large dictionary
self.Width = config['width']
self.Height = config['height']
self.Text = config['text']
self.Font = config['font']
etc...
很简单:
for key, value in config.iteritems():
# Customize key here, for example transform 'text_height' to 'TextHeight' or
# use 'key.title()' to obtain titlecased keys...
setattr(self, key, value)
你可能想要做key.title()
,但实例属性建议是在python全部小写。
使用'key.title()'转换“宽度”键“宽”属性。 – PaulMcG
@Paul:你快了;) – GaretJax
考虑多字键的情况可能会很好。例如,应将'config ['text_height']'分配给'self.TextHeight'? –