正确调用函数内的变量

时间:2014-05-06 07:26:14

标签: python

作为一个例子

def Test():
    Function = 'one'

print(Function)

如何做到这一点? 目前我

NameError:名称'功能'未定义

2 个答案:

答案 0 :(得分:5)

你做不到。 Function仅在Test()方法中定义。

如果你愿意,你应该让方法返回字符串,如下所示:

def Test():
    Function = 'one'
    return Function

a = Test()
print(a)

答案 1 :(得分:4)

该变量超出了该函数的范围。要么调用该函数,要么在最坏的情况下,您也可以使用global关键字。

方式1(更好的选择):

def Test():
    Function = 'one'
    return Function

#If you print Function now, you will get the name error!
print(Function)

>>> NameError: name 'Function' is not defined
# If you call the function that works!!

print (Test())
>>> one

方式2(更糟糕的一个):

>>> Function=''
>>> def Test():
        global Function
        Function = 'one'


>>> print(Test())
None
>>> print(Function)
one
>>> 
相关问题