python同一个类的不同实例的属性的值会受list.append()影响吗?
天蓬老师
天蓬老师 2017-04-17 17:52:36
0
2
287

先放代码:(python2.7.10)

class Res(object):
    x = []
    def __init__(self, t):
        for i in t:
            self.x.append(i)

A = Res(['a', 1])
B = Res(['b', 2])

print A.x
print B.x

输出结果是:

['a', 1, 'b', 2]
['a', 1, 'b', 2]

按理说不应该各是各的吗?

改成下面这种形式就好了

    def __init__(self, t):
        self.x = t

输出:

['a', 1]
['b', 2]

请问这个问题是 list.append() 导致的吗?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
黄舟

This is where you should read the basic tutorials

class Res(object):
    x = []
    def __init__(self, t):
        for i in t:
            self.x.append(i)
        

x here is not an instance variable, but a class variable. The difference between class variables and instance variables is that the former is common to all objects, while the latter belongs to each instance.
self.x.append(i) dereferences member variables first when dereferencing x, but you have not initialized the member variable named x before, so the last dereference is the class variable

class Res(object):
    x = [1, 2]

    def __init__(self, t):
        # 直接使用,解引用为成员变量,去掉self.x=3,解引用为类变量
        self.x = 3
        print self.x
大家讲道理
class Res(object):
    def __init__(self,t):
        self.x=[]
        for i in t:
            self.x.append(i)

As @zwillon said, when self.x in your code cannot find instance attributes, the higher-level class attributes will be used. Writing instance properties like above is the correct approach.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!