简体   繁体   English

如何使用函数更改返回函数/更改变量?

[英]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.在意识到我需要再次运行MyText变量之前,我不知道该怎么做。

I intend to call this text by running something along the lines of print(Text.MyText) which doesn't update after running Text.AddMoreText()我打算通过在运行Text.AddMoreText()后不更新的print(Text.MyText)行运行一些东西来调用此文本

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.我不知道的是,返回函数会保留其值,因此当我运行print(Text.MyText) Text.AddMoreText() print(Text.MyText)它会显示相同的文本两次。

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.这使得.my_text成为每次检索.my_text都会重新计算的动态属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM