首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python声明数组/列表是静态和全局的

Python声明数组/列表是静态和全局的
EN

Stack Overflow用户
提问于 2018-06-03 07:56:03
回答 1查看 642关注 0票数 0

我正在努力学习蟒蛇。我正在编写一个小程序,它在静态数组中保存一些数字或字符串。我希望我的函数将变量保存在单个数组中。但是当我完成我的函数后,数组也消失了。如何在python中使我的数组成为静态数组?我想在几个函数中对其进行更改。

代码语言:javascript
复制
py_ppl = []  

def Dong():

    alc1 = alc.get()
    alc2 = alc1
    alc1 = [0]

    py_ppl.append(alc1[0])
    py_ppl.append(alc2)

我的意思是像这样的东西。我和Tkinter Gui一起得到了alc。

EN

回答 1

Stack Overflow用户

发布于 2018-06-03 08:48:15

这个使用类变量的示例可能会对您有所帮助。在init中声明的变量对于类的每个实例都是局部的,而在类顶部声明的变量对于类的所有实例都是全局的。

代码语言:javascript
复制
class funkBox:
    globalToBox = [] # our class variable
    def __init__(self):
        pass         # our do nothing constructor
    def funk(self,elm): # our function 
        self.globalToBox.append(elm)
    def show(self):     # for demonstration
        print(self.globalToBox)

a = funkBox() #create one instance of your function holder
b = funkBox() #and another
a.funk("a")   #call the function on the first instance
b.funk("b")   # call the function again 
a.show()      # show what instance a has 
b.show()      # and b

打印

代码语言:javascript
复制
['a', 'b']
['a', 'b']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50662164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档