在类实例初始化之后,有没有办法更改类内列表中的变量(抱歉,听起来比实际情况复杂多了!)
我正在编写一个游戏,并将所有显示文本作为数组元素存储在“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
创建该字符串时,将当前值
globalv
合并为一个字符串。创建该字符串后更改globalv
对该字符串的值没有影响。您可以使用setter和print方法来完成此任务:那就这样说吧:
答案很简单
函数返回带有插值的字符串的副本。 所以你的课程包含:
当您将全局var更改为soemthing时,不会重新计算该字符串
而且这个字符串副本是不可变的,所以你的类持有一个数组,这个数组是可静音的,但它持有的只是一个已经解析的字符串,值为7,所以更改global不会影响这个stirng
代码工作正常。我不知道你在期待什么
将globalv转换为文本并将其存储在对象的文本中。当您稍后回来时,该文本字符串与您留下的文本字符串一样。您是否希望它会因为更改了globalv的值而发生神奇的变化?这有点像给自己拍照,换衣服,期望照片能换得和你的新衣服相配。变量不是这样工作的
也许你需要一个两步走的方法:
有帮助吗
相关问题 更多 >
编程相关推荐