实例化的Object携带先前的函数范围状态

时间:2015-01-28 00:05:39

标签: python list object state

新的实例化对象" c"将带有以前的状态" c"在函数中我不知道为什么?

def findNonAndConMax(ar):
c = con()
n = non()
print "The Begining    ",c.theList
for x in ar:
    print "this is x   ",x
    if x < 0:
        print c.theList
        if n.neg == 0 or n.neg < x:
            n.neg = x
        c.theList.append(c.theList[c.current])
        c.current += 1
        c.theList[c.current] += x
        print "The End  ",c.theList
    else:
        n.pos += x
        c.theList[c.current] += x
print "MaX   ",c.max(), n.max()

class non():
    pos = 0
    neg = 0

    def __init__(self):
        self.pos = 0
        self.neg = 0

    def max(self):
        if self.pos == 0:
            return self.neg
        else:
            return self.pos

class con():
    theList = [0]
    current = 0

    def __init__(self):
        theList = [0]
        current = 0

    def max(self):
        print self.theList
        return max(self.theList)

T = int(raw_input())
for i in range(T):
    n = int(raw_input())
    ar = [int(x) for x in raw_input().split()]
    findNonAndConMax(ar)

如果您使用此代码,请输入

2 
4 
1 2 3 4
6
2 -1 2 3 4 -5

你会得到

The Begining     [0]
this is x    1
this is x    2
this is x    3
this is x    4
MaX    [10]
10 10
The Begining     [10]
this is x    2
this is x    -1
[12]
The End   [12, 11]
this is x    2
this is x    3
this is x    4
this is x    -5
[12, 20]
The End   [12, 20, 15]
MaX    [12, 20, 15]
20 11

因此,当再次调用该函数时,con对象将从前一个对象中携带其值,并保留其状态。

为什么会这样?

1 个答案:

答案 0 :(得分:0)

在我看来,__init__方法中存在一个错误:

class con():
    theList = [0] # This is a class attribute
    current = 0 # This is a class attribute

    def __init__(self):
        theList = [0] # This is nothing and will be forgotten as soon as init finishes
        current = 0 # This is nothing too

    def max(self):
        print self.theList # This will print the class attribute
    return max(self.theList)

如果您希望theList成为实例属性,则需要使用self.theList进行设置。