简体   繁体   English

如何使用字典键,值对来设置类实例属性“pythonic”?

[英]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)

您将使用setattrsetattr(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.

相关问题 Pythonic方法使键/值对成为字典 - Pythonic way to make a key/value pair a dictionary 如何在条件语句中使用嵌套在列表中的字典键值对的值? - How do I use the value of a key-value pair of a dictionary nested inside a list in a conditional statement? 如何使用列表的元素来设置字典的键和值? - How do I use elements of list to set the key and value of dictionary? 如何检查字典中是否存在键值对? 如果一个键的值是字典 - How do I check if a key-value pair is present in a dictionary? If the value of one key is a dictionary 如何以 pythonic 方式对 class 的不同属性使用相同的 getter 和 setter 属性和函数? - How do I use same getter and setter properties and functions for different attributes of a class the pythonic way? 如何在Python中将新的一组键值对添加到字典中? - How to append a new set of key,value pair to a dictionary in Python? 如何从python中的字典中提取电子邮件作为键值对? - How do I extract emails from dictionary in python as key value pair? 我怎样才能只使用一个字典并能够 output 与密钥对相关的第三个值? - How can I only use one dictionary and be able to output a third value related to the key pair? 如果密码在字典和键值对中,我如何解决此程序,以便使输入正常工作 - How do i fix this program so it makes the input work if the password is in the dictionary and key value pair 如何确定 Python 的字典中是否存在另一个键:值对? - How do I find out if another key:value pair exists in a dictionary in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM