在python中动态加载属性

问题描述 投票:0回答:1

我想在python中动态加载属性。我应该使用房产还是有更好的方法?这是一个例子:

class Test:

    def __init__(self):
        self.__datas = None
        self.id = 30

    def loadDatas(self):
        self.__datas = {"a": "Hello", "b": "Hi"}


Test = Test()
test.a  // Call loadData and return "Hello"
test.c  // raise error
test.id // print '30'
python properties
1个回答
0
投票

您可以为数据字典的每个元素更新Test .__ dict__,这是一种方法。

class Test:
    def __init__(self):
        self.__data = {'a': 'Hello', 'b': 'Hi'}
        self.__dict__.update(self.__data)
        self.id = 30

    def add(self, key, value):
        self.__data.update({key: value})
        self.__dict__.update(self.__data)


test = Test()
print(test.a)
# print(test.c) raises error
# print(test.id) OK
test.add('c', 'b')
# print(test.c) now ok
© www.soinside.com 2019 - 2024. All rights reserved.