3 ms·
For those who just want a simple a.b instead of a['b'], use this: class Obj(): def __init__(self, d): self.__dict__ = d d = Obj({ 'a': 1,
by fuzzythinker 9y ago
For those who just want a simple a.b instead of a['b'], use this:
class Obj():
def __init__(self, d):
self.__dict__ = d
d = Obj({
'a': 1,
'b': 2,
})
print(d.a)
- yeukhon 9y agoI am guilty of writing classes which are really simple, but only writing a class for the sake of consistency across my codebase. Although there is this PyCon talk from 2012 advocating not to write classes if there is only one or two methods. [1] [1]: https://news.ycombinator.com/item?id=3717715 https://news.ycombinator.com/item?id=3717715
- theptip 9y agoThese days (Python >= 3.3) SimpleNamespace is a more concise way of doing this: from types import SimpleNamespace d = SimpleNamespace(a=1, b=2) print(d.a)
- gshulegaard 9y agoHaha neat, that means this works very cleanly as a conversion mechanism: my_dict = { 'a': 1, 'b': 2 } d = SimpleNamespace(**my_dict) print(d.a)