从字符串实例化对象变量

2024-10-04 09:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,在伪代码中:

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"]

我将如何实现这一点?你知道吗

提前谢谢


Tags: key代码inselffordatainitvalue
2条回答

dict分配给内置的__dict__以获得更大的简化:

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

您正在查找__getattr__,如果插槽不存在,将调用它。你知道吗

class Example:
    def __init__(self, dict):
        self.dict = dict
    def __getattr__(self, prop):
        return self.dict[prop]

相关问题 更多 >