D
D
Dmitry Petrik2017-03-10 15:28:21
Python
Dmitry Petrik, 2017-03-10 15:28:21

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

If the user saves the file, then I do it simply:
self.code = self.new_code
And I have a lot of such properties. Maybe somehow more elegantly you can solve the problem of tracking parameter changes?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tirael78, 2017-03-10
@Flexo

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))

at the output we get
is_change False
We changed the data in self.code
is_change True
Here we saved the data to disk
is_change False

G
GavriKos, 2017-03-10
@GavriKos

And I have a lot of such properties.

To encapsulate in a class means, and where you need to use either it or its successor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question