如何在函数调用在python中完成时访问函数的局部变量? [英] How to access Local variables of functions when the function call has finished in python?

查看:134
本文介绍了如何在函数调用在python中完成时访问函数的局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上发现,当函数调用完成后,函数的局部变量不能从外部访问。我尝试执行该程序,但是它引发了一个错误,那个变量没有被定义。我的代码是

  xyz = list()
n = 0
def长度(g):
i = 0
n = g
v = input(no of)
while i< v:
c = input(输入第一维:)
j =输入(输入第二维:)
i = i + 1
xyz.append(c)
xyz.append(j)
返回c
返回j
返回n
def prod():
全局c
在xyz中为i:
如果n print上传另一个
elif n == c和n == j:
printAccepted
else:
print裁剪
length(input(输入长度))
prod()
print xyz

它会抛出像这样的错误


追溯(最近调用最后一次):
文件C:\Python27\pic.py ,第32行,在
prod()
中`文件C:\Python27\pic.py,第2行1,prod
if n


解决方案

我想这是你想做的事情

  xyz = list()
n = 0
def长度(g):
i = 0
n = g
v = input(no of)
global xyz
while i< v:
c = input(输入第一维:)
j = input(输入第二维:)
i = i + 1
xyz.append(c)
xyz.append(j)
return c,j,

$ b def prod():
global xyz
c,j,n = length(input(ENter the length))
for i in xyz:
if n printUpload another
elif n == c and n == j:
printAccepted

$ print b



$ b $
$ b

输出

 长度2 
no 2
输入第一维度: 1
输入第二维:2
裁剪
裁剪
[1,2]


I found on the net that local variables of functions can't be accessed from outside when the function call has finished.I try to execute the program but it throws an error that variable is not defined. My code is

xyz=list()
n=0
def length(g):
    i=0
    n=g
    v=input("no of")
    while i<v:
        c=input("Enter the 1st dimension:")
        j=input("Enter the 2nd dimension:")
        i=i+1
        xyz.append(c)
        xyz.append(j)
        return c
        return j
        return n
def prod():
    global c
    for i in xyz:
        if n<c and n<j:
            print "Upload another"
        elif n==c and n==j:
            print "Accepted"
        else:
            print "Crop it"
       length(input("ENter the length"))
       prod()
       print xyz

It throws error like this

Traceback (most recent call last): File "C:\Python27\pic.py", line 32, in prod() `File "C:\Python27\pic.py", line 21, in prod if n

解决方案

I guess this is what you would want to do

xyz=list()
n=0
def length(g):
    i=0
    n=g
    v=input("no of")
    global xyz
    while i<v:
        c=input("Enter the 1st dimension:")
        j=input("Enter the 2nd dimension:")
        i=i+1
        xyz.append(c)
        xyz.append(j)
        return c,j,n


def prod():
    global xyz
    c,j,n = length(input("ENter the length"))
    for i in xyz:
        if n<c and n<j:
            print "Upload another"
        elif n==c and n==j:
            print "Accepted"
        else:
            print "Crop it"

prod()
print xyz

Output

ENter the length 2
no of 2
Enter the 1st dimension: 1
Enter the 2nd dimension: 2
Crop it
Crop it
[1, 2]

这篇关于如何在函数调用在python中完成时访问函数的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆