Search code examples
pythonfunctionclassvariablesreturn

How to alter return function/change variable using a function?


I was wondering how I can have a changing variable from a function.

I attempted:

class Text():
  File=open("SomeFile.txt", "r")
  MyText=(File.read()+MoreText)
  def AddMoreText():
    MoreText=("This is some more text")

before realising that I needed to run the MyText variable again which I'm not sure how to do.

I intend to call this text by running something along the lines of print(Text.MyText) which doesn't update after running Text.AddMoreText()

I then tried:

class Text():
  global MoreText
  File=open("SomeFile.txt", "r")
  def ChangeTheText():
    return(File.read()+MoreText)
  MyText=ChangeTheText()
  def AddMoreText():
    MoreText=("This is some more text")

What I didn't know was that the return function preserves its value so when I ran print(Text.MyText) Text.AddMoreText() print(Text.MyText) it displayed the same text twice.


Solution

  • I think you want something like:

    class Text:
        def __init__(self):
            self.parts = []
            with open('SomeFile.txt', 'r') as contents:
                self.parts.append(contents.read())
            self.parts.append('More text')
    
        def add_more_text(self, text):
            self.parts.append(text)
    
        @property
        def my_text(self):
            return ''.join(self.parts)
    

    This makes .my_text a dynamic property that will be re-computed each time .my_text is retreived.