如何去除代码中的全局变量?

2024-06-09 08:48:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我坐了整整一个星期,我不知道如何摆脱这些global points。在

这里我定义points。在

def init():
   global points, hidden_password, hidden_password2, country, used, start_time
   points = 0
   hidden_password = []
   hidden_password2 = []
   country = ""
   used = []
   start_time = datetime.now()
   welcome()
   choice()

然后从choice到choice(),到play_game(),再到{},这里我第一次使用点,程序一直工作到var points达到5。在

^{pr2}$

然后它转到checking(),从检查到letter(),然后到checking_password(),如果用户没有猜到正确的字母,它会将1加到points并返回它。在

def checking_password(number):
    global points, hidden_password2, hidden_password
    if hidden_password2 == hidden_password:
        points += number
    time.sleep(1)
    print("\n Boo! You have +", number, "penalty points!")
    time.sleep(1)
    hidden_password2 = hidden_password
    if points < 4:
        manage_graphics(points)
    elif points == 4:
        manage_graphics(points)
        print(" Hint: It's a capital of " + country + ".")
    elif points >= 5:
        manage_graphics(5)
    return points

如果有人想要,这里有一个完整的代码:https://codeshare.io/aYBAzb


Tags: numbermanagetimedefpasswordglobalcountrystart
1条回答
网友
1楼 · 发布于 2024-06-09 08:48:13

可以使用类来存储属性。在

Class Game:
    def __init__():
        points = 0
        self.hidden_password = []
        self.hidden_password2 = []
        self.country = ""
        self.used = []
        self.start_time = datetime.now()
        self.welcome()  # This should be in main function
        self.choice()  # This should be in main function
    def choice(self, ...):
        pass        
    def welcome(self, ...):
        pass
    def guessing_capital(self, ...):
        pass
    def checking_password(self, ...):
        pass

相关问题 更多 >