python-3.x 未定义播放器

a64a0gku  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(154)

我有一些问题与球员没有定义的错误,这是错误和代码,我已经把链接到它的图片。我很新的Python,我不明白的错误,我会很高兴,如果有人可以帮助。
Player not defined errorsCodeCode的一个字符串

sigwle7e

sigwle7e1#

我已经创建了一个最小的工作代码关于你的附件图片。大多数情况下,你的全局变量处理是不正确的。你可以在下面的代码中找到我的意见作为评论。

产品代码:

# 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))

相关问题