-1

A class feature in Python3 like the following:

>>> some_instance.last_edited
None # No change was made
>>> some_instance.content = "I'm making a change to the content(attribute) of this class instance"
>>> some_instance.last_edited
datetime.datetime(2020, 7, 5, 17, 14, 10)  # My local time at the time of writing
Hong Z
  • 192
  • 2
  • 5
  • So when `some_instance.content ` is changed you want `some_instance.last_edited` to be updated automatically? – Feodoran Jul 05 '20 at 06:36
  • @Feodoran Yes! How can you do it? – Hong Z Jul 05 '20 at 06:39
  • Does this answer your question? [What's the pythonic way to use getters and setters?](https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters) – MisterMiyagi Jul 05 '20 at 09:25

2 Answers2

2

You can use the @property decorator (see Python docs) and its corresponding setter to automatically call a method when setting an attribute. In that method you may update the last_edited timestamp:

import datetime
import time

class Store:
    
    def __init__(self, content=''):
        self.content = content
    
    @property
    def content(self):
        return self._content
    
    @content.setter
    def content(self, value):
        self._content = value
        self.last_edited = datetime.datetime.now()
        
s = Store()
print(s.last_edited)
time.sleep(1)
s.content = 'a'
print(s.last_edited)

Output:

2020-07-05 08:49:53.057723
2020-07-05 08:49:54.059379
Feodoran
  • 1,752
  • 1
  • 14
  • 31
0

Maybe this can help. I know it is not exactly as you want, but it might solve your problem.

class C:

    def __init__(self, content):
        self.content = content
        self.last_edited = None

    def editContent(self, newContent):
        self.content = newContent
        self.last_edited = datetime.now()

It works if you use

some_instance.editContent("New content")

instead of

some_instance.content = "New content"