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

2024-09-23 14:30:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在类实例初始化之后,有没有办法更改类内列表中的变量(抱歉,听起来比实际情况复杂多了!)

我正在编写一个游戏,并将所有显示文本作为数组元素存储在“text”类的实例中。我编写了以下示例程序来测试我要做的事情:

#****************************************#
#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

Tags: ofthetotextfromformatprintsmax
3条回答

创建该字符串时,将当前值globalv合并为一个字符串。创建该字符串后更改globalv对该字符串的值没有影响。您可以使用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

那就这样说吧:

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

答案很简单

str.format()

函数返回带有插值的字符串的副本。 所以你的课程包含:

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

当您将全局var更改为soemthing时,不会重新计算该字符串

而且这个字符串副本是不可变的,所以你的类持有一个数组,这个数组是可静音的,但它持有的只是一个已经解析的字符串,值为7,所以更改global不会影响这个stirng

代码工作正常。我不知道你在期待什么

将globalv转换为文本并将其存储在对象的文本中。当您稍后回来时,该文本字符串与您留下的文本字符串一样。您是否希望它会因为更改了globalv的值而发生神奇的变化?这有点像给自己拍照,换衣服,期望照片能换得和你的新衣服相配。变量不是这样工作的

也许你需要一个两步走的方法:

  1. 创建一个属性来保存值,例如self.value
  2. 编写一个显示对象属性的方法;在该方法中,访问self.value的current值,在生成的显示字符串中使用该值

有帮助吗

相关问题 更多 >