如何使用字典键,值对设置类实例属性"pythonic" ly? [英] How do I use dictionary key,value pair to set class instance attributes "pythonic"ly?

查看:97
本文介绍了如何使用字典键,值对设置类实例属性"pythonic" ly?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一些Python类用作多变量数据结构,然后将其用于各种任务.在某些情况下,我喜欢用各种值集填充类.默认参数文件名"ho2.defaults"如下所示:

I have created some Python classes to use as multivariate data structures, which are then used for various tasks. In some instances, I like to populate the classes with various value sets. The default parameter filename "ho2.defaults" would look something like this:

name = 'ho2'
mass_option = 'h1o16'
permutation = 'odd'
parity = 'odd'
j_total = 10
lr = 40
br = 60
jmax = 60
mass_lr = 14578.471659
mass_br = 1781.041591
length_lr = ( 1.0, 11.0, 2.65 )
length_br = ( 0.0, 11.0, 2.46 )
use_spline = True
energy_units = 'au'
pes_zpe = -7.407998138300982E-2
pes_cutoff = 0.293994

当前,我通过从文件中读取所需的键和值对来创建字典,现在我希望通过"pythonic"方式将这些字典键用作类实例变量名称,即

Currently, I create a dictionary from reading the desired key,value pairs from file, and now I'd like a "pythonic" way of making those dictionary keys be class instance variable names, i.e.

# Instantiate Molecule Class
molecule = Molecule()

# Create Dictionary of default values
default_dict = read_dict_from_file(filename)

# Set populate class instance variables with dictionary values
for key,value in default_dict:
    molecule.key = value

因此可以使用字典的键值对来设置Class的实例变量"molecule.name".我可以手动完成此操作,但是我敢肯定有更好的方法可以遍历它.实际上,字典可能很大,我希望用户选择他们要填充的值,以便字典可以更改.我在这里想念什么?

So the Class's instance variable "molecule.name" could be set with the dictionary key,value pair. I could do this by hand, but I'ms sure there is a better way to loop through it. In actuality, the dictionary could be large, and I'd rather allow the user to choose which values they want to populate, so the dictionary could change. What am I missing here?

推荐答案

简单方法是:

vars(molecule).update(default_dict)

这将破坏所有先前存在的属性.对于更精致的方法,请尝试:

This will clobber any pre-existing attributes though. For a more delicate approach try:

for name, value in default_dict.items():
    if not hasattr(molecule, name):
        setattr(molecule, name value)

这篇关于如何使用字典键,值对设置类实例属性"pythonic" ly?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆