Python2.7局部变量的作用类似于全局变量

2024-09-29 23:18:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个功能包含在两个单独的文件。在

这些函数相似,并且对其中的局部变量使用相同的名称。传递给每个函数的参数“eachtickerlist”也是相同的。eachtickerlist是如下所示的列表

[[ticker,price,year,month,day,seconds from epoch],[ticker,price,year.........

由于某些原因,当执行函数2时,每个函数“amlist”中的局部变量将保留来自函数1的数据,即使它在第二个函数中被重新初始化,即使它是一个局部变量。我知道这一点是因为当我在函数2的末尾打印出'amlist'来测试它时,字符串'undefined'、'up'或'down'会被列出2次。如果我不在主程序中调用函数1,这就不会发生,这证明函数1中发生的事情会影响函数2……我完全不明白。在

在主程序中,我调用每个函数,如下所示:

^{pr2}$

功能1:

def upsvsdowns(eachtickerlist):

amlist=[]
for thing in eachtickerlist:
    if (thing[5]=='8'):
        amlist.append(thing)


    else:
        pass


try:
    amlist[0].append('undefined')
    length=len(amlist)


    for x in range(1,length):
        price=float(amlist[x][1])
        yesterdaysprice=float(amlist[(x-1)][1])

        if ((price-yesterdaysprice)>0):
            amlist[x].append('up')

        else:
            amlist[x].append('down')

    upcount=0
    totalcount=0
    for y in amlist:
        if (y[7]=='up'):
            upcount=upcount+1
            totalcount=totalcount+1

        else:
            totalcount=totalcount+1

    percentage=round(float(upcount)/float(totalcount),3)
    returnlist=[amlist[0][0],str(percentage)]

    return (returnlist)

except (IndexError):
    returnlist=[eachtickerlist[0][0],'No Data']
    return (return list)

这里是函数2:

def swings(eachtickerlist):

amlist=[]
for thing in eachtickerlist:
    if (thing[5]=='8'):
        amlist.append(thing)


    else:
        pass


try:
    amlist[0].append('undefined')
    length=len(amlist)


    for x in range(1,length):
        price=float(amlist[x][1])
        yesterdaysprice=float(amlist[(x-1)][1])

        if ((price-yesterdaysprice)>0):
            amlist[x].append('up')

        else:
            amlist[x].append('down')

    upcount=0
    downcount=0
    ups=[]
    downs=[]

    print amlist

    for y in amlist:
        if (y[7]=='up'):

            if (downcount!=0):
                downs.append(downcount)

            else:
                pass

            downcount=0
            upcount=upcount+1


        elif (y[7]=='down'):

            if (upcount!=0):
                ups.append(upcount)
            else:
                pass
            upcount=0
            downcount=downcount+1

        if (upcount!=0):
            ups.append(upcount)
        elif (downcount!=0):
            downs.append(downcount)
        else:
            pass
    #print ups
    #print downs


    try:
        averageup=round(sum(ups)/float(len(ups)),3)

    except(ZeroDivisionError):
        averageup=round(0.0,3)

    try:
        averagedown=round(sum(downs)/float(len(downs)),3)

    except(ZeroDivisionError):
        averagedown=round(0.0,3)


    returnlist=[amlist[0][0],str(averageup),str(averagedown)]

    return (returnlist)

except (IndexError):
    returnlist=[eachtickerlist[0][0],'No Data']
    return (return list)

这是第二个函数中print语句的输出。注意每个列表中有2个未定义的,向上和向下的。在

['AAIT', '35.09', '2014', '7', '28', '8', '2409480.0', 'undefined', 'undefined'], ['AAIT', '35.21', '2014', '7', '29', '8', '2494662.0', 'up', 'up'], ['AAIT', '40', '2014', '7', '29', '8', '2494662.5', 'up', 'up'], ['AAIT', '42.3', '2014', '7', '29', '8', '2494663.0', 'up', 'up']]

任何帮助都将不胜感激。在

-布兰登


Tags: 函数inforiffloatpriceelsething
1条回答
网友
1楼 · 发布于 2024-09-29 23:18:17

不,函数之间不共享局部变量。局部变量完全存在于一个函数中。但与其他编程语言不同,变量不是对象。它们只是已知物体的名称。另一方面,对象可以在被调用函数返回后很长时间内保持。在

让我们考虑一个更简单的程序:

def func1(arg):
    arg.append('Hello from Func1!')
    print arg

def func2(arg):
    arg.append(2)
    print arg


main_list = [9,8,7]

func1(main_list)
func2(main_list)

该程序的输出为:

^{pr2}$

如您所见,func2中的局部变量arg中包含来自func1的消息!但它只被添加到func1中的局部变量中。那么,这是否意味着一个上下文中的名称arg与另一个上下文中的名称arg有某种关联吗?在

没有

Python中的P>与C或C++不同,变量不通过值传递到子程序。相反,被调用方中的参数绑定到调用方中存在的同一对象。这有点像其他编程语言中的传递引用。在

考虑一下这个:

def func(i):
   print id(i)

a="Some string"
print id(a)
func(a)

在这个例子中,我们打印出一个对象的id()。每个对象都有一个id(),并且没有两个对象同时具有相同的id。在

这个例子在我的电脑上的输出是:

140601888512880
140601888512880

如您所见,调用者中的a和被调用者中的i是同一个对象。一个不是另一个的复制品,它们是完全相同的对象。在

这些和你的计划有什么关系?在

在程序中,修改传入列表。因为没有复制,所以实际上是在修改原始列表。当原始列表传递给下一个函数时,它将接收修改后的列表。在

下面是如何修改upsvsdowns中传入的列表对象:

amlist.append(thing) # This doesn't modify the original object, but it does
                     # set up the modification. After this line completes,
                     # amlist[i] and eachtickerlist[j] are both references
                     # to the same object (for some value of i and j).

amlist[0].append('undefined') # This statement modifies the object referenced by
                              # amlist[0]. Since that object is also referenced by
                              # eachtickerlist[j] (for some j), you have now
                              # stored the word 'undefined' "inside" the object
                              # referenced by eachtickerlist. Since that object
                              # is also referenced by the caller's eachtickerlist,
                              # the change is permanent and globally visible

有关更清楚的解释,请参见the docs,尤其是§3.1。在

相关问题 更多 >

    热门问题