-1

I have a class C with n instance attributes a1, a2, a3, ..., an and a dictionary

d = {'ai': x, 'aj': y, 'ak': z, ..., 'be': p, 'bf': q, 'bg': r, ...}

containing values for some of those instance attributes and some other entries.

An object O = C() is constructed. Is there a better way to pass the attribute values that doing

O.ai = d['ai']
O.aj = d['aj']
O.ak = d['ak']

... and, so on?

phydev
  • 13
  • 6
  • Do the answers to this [question](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) help at all? – quamrana Oct 27 '22 at 09:28
  • @quamrana Not sure if it's related, given the accepted answer. But using `getattr()` might work. – phydev Oct 27 '22 at 09:37

1 Answers1

0

If C is a regular class, you can update its __dict__ directly:

class C:
    def update(self, d):
        vars(self).update(d)


c = C()
c.update({'foo': 123, 'bar': 456})
print(c.foo)
print(c.bar)

To make your IDE or mypy happy, it would make sense to declare these attributes in the class body or __init__:

class C:
    foo: int
    bar: int
    ...etc
gog
  • 10,367
  • 2
  • 24
  • 38
  • Does it also work when the dict you're updating with contain some extra keys that aren't instance attributes of C? – phydev Oct 27 '22 at 09:42
  • @phydev: sure, those declarations are just for documentation/typechecking purposes, python itself doesn't care. – gog Oct 27 '22 at 10:36