Answer the question
In order to leave comments, you need to log in
How to track if a parameter in a class has changed in python?
I write something like notepad++. The file opens in the editor, and if the user has changed the text, but has not yet saved it, then the tab with the file name should turn red, such as there are unsaved changes. To do this, I created a class that describes the file. And there he made the self.code property, the original contents of the file are written to it. And I added another property self.new_code, I write the text changed by the user into it. Then I just compare
if self.code != self.new_code:
return True
self.code = self.new_code
Answer the question
In order to leave comments, you need to log in
Of course you can. You need to use descriptors, in a very lightweight form, something like:
class Notepad:
def __init__(self):
self._is_change = False
self.code = None
def __setattr__(self, key, value):
if key is 'code' and value is not None:
self.__dict__['_is_change'] = True
self.__dict__['code'] = value
else:
self.__dict__[key] = value
def save(self):
print('Тут вот сохранили данные на диск')
self._is_change = False
@property
def is_change(self):
return self._is_change
note_text = Notepad()
print('is_change {}'.format(note_text.is_change))
print('Изменили данные в self.code')
note_text.code = 'bla bla'
print('is_change {}'.format(note_text.is_change))
note_text.save()
print('is_change {}'.format(note_text.is_change))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question