![](/img/trans.png)
[英]How do i use a variable that is defined inside of a function, outside of a function?
[英]Python - If I create a variable inside a function, how can I then use it outside the function?
我想在函数内部创建一个变量,然后在函数外部使用该变量。 有没有办法做到这一点? 例如:
def Function():
score = 5
Function()
print(score)
谢谢 :)
您有几种选择(拥有更多选择的人,随时可以贡献力量):
方法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)
请注意,在第一种方法中,您需要在函数外部声明变量score才能起作用。
你必须退货
def Function():
score = 5
return score
score=Function()
print(score)
从技术上讲,您可以使用global
关键字:
def Function():
global score
score = 5
Function()
print(score)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.