How to update a property automatically if other property changes in python?

Viewed 19

I have a class like this

class Data():
    def __init__(self,pDict):
        # its take dict as parameter
        # my dict is pDict={'one':1,'two':2,'Three':3......its lot of keys}
        self.data=pDict
        self.one=pDict['one']
        self.two=pDict['two']
        self.Three=pDict['Three']
        .
        .
        .
        .
        .

if set new to value to property.then it need to update on main dict also how?

d=Data()
print(d.one)# output: 1
print(d.two)# output: 2
d.two=22
print(d.two)# output: 22
print(d.data)# output: {'one':1,'two':2,'Three':3......}
# i need change this also

how to update automatically.

1 Answers

What you're doing isn't going to work, but you can import the dictionary into the __dict__ entry in the object:

class Data():
    def __init__(self,pDict):
        self.__dict__.update(pDict)

dct= {'one':1, 'two':2, 'three':3}
d = Data(dct)
print(d.one)
print(d.two)
d.two=22
print(d.two)
print(d.__dict__)

Output:

1
2
22
{'one': 1, 'two': 22, 'three': 3}

IF you want those changes reflected in the original dictionary, then you'll have to do something with __getattr__ and __setattr__, but that's not really a good practice. Writing to an object should not have outward side effects.

Related