简体   繁体   English

Python-使用字符串列表作为类数据成员。 当字符串包含变量时,变量不会更新

[英]Python - Using list of strings as class data member. When strings contain variables, variables don't update

Is there a way to change variables within lists within classes after the class instance has been initialized? 类实例初始化后,是否可以更改类列表中的变量? (Sorry, sounds more complicated than it is!) (抱歉,听起来比它复杂!)

I'm writing a game and storing all of my display text as array elements in instances of a "Text" class. 我正在编写一个游戏,并将所有显示文本存储为“ Text”类实例中的数组元素。 I wrote the following example program to test what I'm trying to do: 我编写了以下示例程序来测试我要执行的操作:

#****************************************#
#INITIALIZE CLASS (to hold text component)
#****************************************#
class Text:
        def __init__(self, array, maxIndex):

            #list of text
            self.list = array

            #number of items in list
            self.max = maxIndex

#set global variable to 7
globalv = 7

#****************************************#
#INITIALIZE VARIABLE-ENHANCED TEXT
#necessary because variables inside class
#data member arrays seem to have a local
#scope, and can't be changed after they
#are initialized
#****************************************#
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

print varLine.list[varLine.max]
#prints 7

#CHANGE VALUE OF globalv:
print "Directly accessing globalv: {}".format(globalv)
#prints 7
print "\nUpdate value of globalv to 9"
globalv = 9
print "Directly accessing globalv: {}".format(globalv)
#prints 9

#Try to change and re-print variable
#doesn't work, despite the fact that "global" has changed outside of the class
print "\nfirst try:"

#call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 7

#Change variable by re-initializing class
print "\nsecond try:"
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

    #call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 9

When you create that string you are concatinating the current value of globalv into a string. 创建该字符串时,您会将globalv的当前值globalv为一个字符串。 Changing globalv after that string been created has no effect on the value of the string. 创建该字符串后更改globalv不会影响该字符串的值。 You can make setter and print methods to accomplish this: 您可以使用setter和print方法来完成此任务:

class Text:
    def __init__(self, strList, valueList, maxIndex):

        #list of text/values
        self.strList = strList
        self.valueList = valueList

        #number of items in list
        self.max = maxIndex

    def printStrAtIndex(self, idx):
        print(self.strList[idx] + str(self.valueList[idx]))

    def setValAtIndex(self, val, idx):
        self.valueList[idx] = val
        return self

    # add new str value pair to the the class
    def addStrAndValue(self, newStr, newValue):
        self.strList.append(newStr)
        self.valueList.append(newValue)
        self.max = len(self.valueList)-1

Then just call it like this: 然后像这样调用它:

varLine = Text(["This line is tied to the value: "], [7], 0)
varLine.printStrAtIndex(0)
varLine.setValAtIndex(9,0)
varLine.printStrAtIndex(0)

Answer is easy. 答案很简单。

str.format()

Function returns copy of string with intrerpolated values . 函数返回具有内插值的字符串的副本。 So Your Class contains : 因此,您的课程包含:

vaeLine.list = ["Copy of formating string with resolved value"]

When You change global var to soemthing this string isn't reevaluated 当您将global var更改为soemthing时,不会重新评估此字符串

And this string copy is immutable so Your class is holding array which is muteable but its holding just an already resolved string with value 7. So changing global doesnt affect this stirng. 而且此字符串副本是不可变的,因此您的类持有的数组是可变的,但它仅持有已解析的值为7的字符串。因此更改全局不会影响此搅动。

The code is working correctly. 该代码正常工作。 I'm not sure what you're expecting. 我不确定您的期望。

You convert globalv to text and store it in an object's text. 您将globalv转换为文本并将其存储在对象的文本中。 When you come back later, that text string is just as you left it. 当您稍后返回时,该文本字符串与您刚离开时的一样。 Are you expecting it to magically change because you changed the value of globalv ? 您是否期望它会因为更改globalv的值而发生神奇的变化? This is somewhat like taking a photograph of yourself, changing clothes, and expecting the photo to change to match your new outfit. 这有点像为自己拍照,换衣服,并期望照片会随着您的新衣服而变化。 Variables don't work that way. 变量不能那样工作。

Perhaps what you need is a two-step approach: 也许您需要的是两步方法:

  1. Create an attribute to hold the value, such as self.value 创建一个属性来保存值,例如self.value
  2. Write a method to display an object's attribute; 编写一种方法来显示对象的属性; within that method, acces the current value of self.value, using that in the display string that you build. 在该方法中,使用您构建的显示字符串中的值访问self.value的当前值。

Does that help? 有帮助吗?

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

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