I'm not so much familiarized with Python classes, but I need to detect changes of instance variables of a given class. According to the documentation, true "private" instance variables do not exist, so in particular I want to detect changes when the instance variable is accessed directly not through a specific method. For example:
class myclass:
def __init__(self):
self.var1 = []
def addelement(self, data):
self.var1.append(data)
print('element',data,'added')
a=myclass()
a.addelement(6)
"element 6 added"
print(a.var1)
[6]
a.var1.append(7)
a.var1
[6, 7]
In the later case I don't know how to detect the added data. I now that methods can be overriding but I would like to know if there is a general approach that allows detecting changes whatever be the variable nature (dict, list, string...). Thank you.
__getattribute__for your class to define whata.var1means, but an adversary could still access the instance variable directly witha.__dict__['var1']instead ofa.var1. You simply cannot do what you want.__getattribute__, I think that's a better answer than mine.__getattribute__can prevent you from accessinga.__dict__. It's still not possible to prevent access, you can still e.g. accesssuper(type(a), a).__getattribute__('var1').__getattribute__is probably overkill; I mentioned it simply because even it can be bypassed (although in a different way than I mentioned, thanks L3viathan). I upvoted your answer for the mention that Python simply doesn't provide privacy protection.