在python中动态加载属性

时间:2017-12-18 14:06:46

标签: python properties

我想在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'

1 个答案:

答案 0 :(得分: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