-2

For example in pseudocode:

class Example:

    def __init__(self, dict):
        for key, value in dict.items():
            self.key = value

a = Example({"objectVariable": ["some", "data"]})
print(a.objectVariable)
>>>["some", "data"]

How would I implement this?

Thanks in advance

Primusa
  • 12,476
  • 3
  • 31
  • 50

2 Answers2

1

Assign dict to the built in __dict__ for greater simplicy:

class Example:
   def __init__(self, dict):
     self.__dict__ = dict
Ajax1234
  • 66,333
  • 7
  • 57
  • 95
  • 1
    `self.__dict__.update(dict)` should be preferred as it is more generally applicable. Also, later changes to the passed `dict` will not be reflected in the instance attributes! – user2390182 Dec 31 '17 at 01:37
  • 1
    A note not to shadow the built-in name `dict` would also be nice. – user2390182 Dec 31 '17 at 01:44
1

You're looking for __getattr__, which will be called if the slot doesn't exist.

class Example:
    def __init__(self, dict):
        self.dict = dict
    def __getattr__(self, prop):
        return self.dict[prop]
Silvio Mayolo
  • 41,871
  • 4
  • 57
  • 86