-2

This question already has an answer here:

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


  • what's the question ? - Chiheb Nexus
  • setattr(self, key, value). - ekhumoro
  • There is no question in your question. - Jörg W Mittag
  • my apologies, i thought the functionality i sought to accomplish would be best expressed in an example. I edited the question to clarify what I'm looking for - Primusa

2 답변


1

Assign dict to the built in __dict__ for greater simplicy:

class Example:
   def __init__(self, dict):
     self.__dict__ = dict


  • 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! - schwobaseggl
  • A note not to shadow the built-in name dict would also be nice. - schwobaseggl

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]

Linked


Related

Latest