How to use a dictionary key, a pair of values ​​to set the attributes of an instance of the pythonic class?

I created several Python classes for use as multidimensional data structures, which are then used for various tasks. In some cases, I like to populate classes with different sets of values. By default, the filename parameter "ho2.defaults" will 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

I am currently creating a dictionary to read the desired key, a pair of values ​​from a file, and now I need a "pythonic" way to make these dictionary keys be the instance names of the instance class, 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

, "." , . , , . , , , . ?

+4
3

:

vars(molecule).update(default_dict)

. :

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

setattr: setattr(molecule, key, value)

+2

, :

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)
0

Source: https://habr.com/ru/post/1615095/


All Articles