This popular question addresses setting instance attributes with keyword arguments. However, I'd like to construct a class whose instances all have the same attributes based on some dictionary. How can this be achieved?
Here's my attempt. It seems I haven't quite understood something about class definitions.
d = {'x': 1, 'y': 2}
# Here's what I'd like to do
class A:
__dict__ = d
# Answer from the linked question that works
class B:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
a = A()
b = B(**d)
# print(A.x) # Has no attribute x
# print(a.x) # Has no attribute x
print(b.x)
This is curious, because both a.__dict__
and b.__dict__
return the same thing.