[英]How do I use dictionary key,value pair to set class instance attributes “pythonic”ly?
I have created some Python classes to use as multivariate data structures, which are then used for various tasks. 我创建了一些Python类作为多变量数据结构,然后用于各种任务。 In some instances, I like to populate the classes with various value sets. 在某些情况下,我喜欢使用各种值集填充类。 The default parameter filename "ho2.defaults" would look something like this: 默认参数文件名“ho2.defaults”看起来像这样:
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
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, ie 目前,我通过从文件中读取所需的键,值对来创建字典,现在我想要一种“pythonic”方式使这些字典键成为类实例变量名,即
# 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
So the Class's instance variable "molecule.name" could be set with the dictionary key,value pair. 因此可以使用字典键,值对设置Class的实例变量“molecule.name”。 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? 我在这里错过了什么?
The simple way is: 简单的方法是:
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)
您将使用setattr : setattr(molecule, key, value)
I'd invert the logic so that the object dynamically answers questions: 我会反转逻辑,以便对象动态回答问题:
class Settings(object):
ATTRS = {'foo', 'bar'}
def __init__(self, defaults):
self.__dict__['data'] = defaults.copy()
def __getattr__(self, key):
if key not in self.ATTRS or key not in self.data:
raise AttributeError("'{}' object has no attribute '{}'".format(
self.__class__.__name__, key))
return self.data[key]
def __setattr__(self, key, value):
self.data[key] = value
s = Settings({'a': 'b', 'foo': 'foo!', 'spam': 'eggs'})
print s.foo
try:
print s.spam
except AttributeError:
pass
else:
raise AssertionError("That should have failed because 'spam' isn't in Settings.ATTRS")
try:
print s.bar
except AttributeError:
pass
else:
raise AssertionError("That should have failed because 'bar' wasn't passed in")
class Molecule(settings):
ATTRS = {'name', 'mass_option', ...}
molecule = Molecule(default_dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.