相关疑难解决方法(0)

python类实例变量和类变量

我在理解类/实例变量如何在Python中工作时遇到了问题.我不明白为什么当我尝试这个代码时,list变量似乎是一个类变量

class testClass():
    list = []
    def __init__(self):
        self.list.append('thing')

p = testClass()
print p.list

f = testClass()
print f.list
Run Code Online (Sandbox Code Playgroud)

输出:

['thing']
['thing', 'thing']
Run Code Online (Sandbox Code Playgroud)

当我这样做时,它似乎是一个实例变量

class testClass():
    def __init__(self):
        self.list = []
        self.list.append('thing')

p = testClass()
print p.list

f = testClass()
print f.list
Run Code Online (Sandbox Code Playgroud)

输出:

['thing']
['thing']
Run Code Online (Sandbox Code Playgroud)

python variables class instance

28
推荐指数
2
解决办法
3万
查看次数

标签 统计

class ×1

instance ×1

python ×1

variables ×1