# Define global variable
current_player = None
class Player(object):
def __init__(self, name):
self.name = name
self.other = 100
def main():
option = input("Option: ")
if option == "1":
start()
def start():
# Use the global variable inside the function.
global current_player
user_name = input("Name: ")
# Assign the Player instance to the global variable.
current_player = Player(name=user_name)
start1()
def start1():
# Use the global variable inside the function.
global current_player
# Get the "name" attribute of the "Player" object.
print("Hello my friend: {}".format(current_player.name))
main()
字符串
输出:
>>> python3 test.py
Option: 1
Name: Bill
Hello my friend: Bill
>>> python3 test.py
Option: 1
Name: Jill
Hello my friend: Jill
型
注:
我建议去掉全局变量的用法。把需要的变量作为参数传递。我已经实现了一个不包含全局变量的版本。
def start():
user_name = input("Name: ")
# Assign the Player instance to the global variable.
current_player = Player(name=user_name)
start1(current_player)
def start1(current_player_info):
# Get the "name" attribute of the "Player" object.
print("Hello my friend: {}".format(current_player_info.name))
1条答案
按热度按时间sigwle7e1#
我已经创建了一个最小的工作代码关于你的附件图片。大多数情况下,你的全局变量处理是不正确的。你可以在下面的代码中找到我的意见作为评论。
产品代码:
字符串
输出:
型
注:
我建议去掉全局变量的用法。把需要的变量作为参数传递。我已经实现了一个不包含全局变量的版本。
型