0

I would like to create a class ("MyClass") that can accept a dictionary as an argument:

>>> d = {'key1', 'value1', 'key2', 'value2'}
>>> obj = MyClass(d)

The dictionary keys can be accessed as attributes:

>>> obj.key1
'value1'

The dictionary keys can be set like attributes:

>>> obj.key2 = 'a new value'
>>> obj.key2
'a new value'

An exception is raised if a key is accessed that wasn't in the dictionary:

>>> obj.key3
AttributeError: 'MyClass' object has no attribute 'key3'

There are also a few valid attributes that aren't in the dictionary but are settable. MyClass would know about them internally.

>>> obj.valid_attribute1 = 'this is a valid attribute'

Other attributes (that aren't valid) aren't allowed:

>>> obj.invalid_attribute = 5
AttributeError: 'MyClass' object has no attribute 'invalid_attribute'

I think this is similar to how a Pandas Series object works:

>>> import pandas as pd
>>> import numpy as np
>>> s = pd.Series(np.array([1,2]),index=['a','b'])
>>> s.a = 3
>>> s
a    3
b    2
dtype: int32
justin
  • 171
  • 8
  • https://stackoverflow.com/questions/2466191/set-attributes-from-dictionary-in-python – Serge Oct 18 '18 at 23:39
  • Possible duplicate of [Accessing dict keys like an attribute?](https://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute) – aydow Oct 18 '18 at 23:39

2 Answers2

0

You are thinking of namedtuple

Assuming your class is named Player

from collections import namedtuple

Player = namedtuple('Player', ['attr1', 'attr2', 'attr3'])
Player(**your_dict) # Assuming your dict has {attr1: v, attr2: v..) etc

You can also initiate it like any other class

player = Player(attr1, attr2, attr3)

Access it's members by

player.attr1

And you cannot set another argument that you didn't set in beginning

player.attrthatdoesnotexist = 1
>>>
'Player' object has no attribute 'attrthatdoesnotexist'
Rocky Li
  • 5,641
  • 2
  • 17
  • 33
0

namedlist (https://pypi.org/project/namedlist/) seems like a pretty decent solution:

>>> from namedlist import namedlist
>>> MyClass = namedlist('MyClass', ['key1','key2'])
>>> d = {'key1': 'value1', 'key2': 'value2'}
>>> obj = MyClass(**d)
>>> obj.key2 = 'a new value'
>>> obj.key2
'a new value'

>>> obj.key3 = 'invalid'

AttributeError: 'MyClass' object has no attribute 'key3'
justin
  • 171
  • 8