Python - 如果我在函数内创建一个变量,那我怎么能在函数外面使用它?

时间:2017-11-14 16:18:21

标签: python function

我想在函数内部创建一个变量,然后在函数外部使用该变量。有没有办法做到这一点?例如:

def Function():
    score = 5

Function()

print(score)

谢谢:)

3 个答案:

答案 0 :(得分:2)

你有几个选择(任何拥有更多,随意贡献的人):

方法1.在函数外部声明变量,将其设置在函数内。

score = None
def Function():
    global score # This tells the function to use the variable above
    score = 5 

Function()

print(score) # Or "print score" if using a different version of python

方法2.返回变量并使用它进行设置。

def Function():
    score = 5
    return score

print(Function()) # This bypasses the need to declare score outside the function.
# print(score) # This would not do anything useful, as score was never declared in this scope.

方法3.使用面向对象的方法。

class App:
    def __init__(self):
        App.score = 5

App()
print(App.score)

请注意,在第一种方法中,您需要在函数外部声明变量得分才能使其起作用。

答案 1 :(得分:0)

你必须退回

def Function():
    score = 5
    return score

score=Function()

print(score)

答案 2 :(得分:0)

从技术上讲,您可以使用global关键字:

def Function():
    global score
    score = 5

Function()
print(score)