我正在构建一个允许用户跟踪篮球成绩的应用程序。例如,如果一支球队射门罚球,他们会按下得分组头球下的“罚球”按钮,并将一分加到显示的分数上。我正在使用Python3.x,我想知道是否可以编写函数参数,这些参数将被指定为home或score分数变量,然后更新指定的分数。目前,我对每支球队的每一种类型的得分都有不同的功能,这意味着我基本上有重复的代码减去“主场”和“客场”的差异。由于与其他软件的接口要求,主场和客场得分都被保存为全局。我是被6个总函数困住了,还是可以编写3,并在调用函数时指定要更新的全局函数?附例非工作代码
global away_score
away_score = 0
global home_score
home_score = 0
def plus_one(inc_score, inc_frame):
inc_score += 1
inc_frame.config(text = inc_score) # this is for interfacing with tkinter发布于 2019-10-17 03:57:59
由于您正在使用tkinter,处理此问题的最好方法可能是利用tkinter变量,在本例中是IntVar。
import tkinter as tk
root = tk.Tk()
away_score = tk.IntVar(value=0)
home_score = tk.IntVar(value=0)
def plus_one(inc_score, inc_frame):
inc_score.set(inc_score.get()+1)
inc_frame.config(text = inc_score.get())
away_but = tk.Button(root,text=0)
away_but.config(command=lambda: plus_one(away_score,away_but))
away_but.pack()
root.mainloop()发布于 2019-10-17 03:54:39
最好不要使用全局变量和重构代码来使用本地变量和字典或对象来存储分数。至于你的问题,你可以这样写:
away_score = 0
home_score = 0
def plus_one(inc_frame, add_to_away: bool = False):
global home_score
global away_score
if add_to_away:
away_score += 1
inc_score = away_score
else:
home_score += 1
inc_score = home_score
# inc_frame.config(text = inc_score) # this is for interfacing with tkinter
if __name__ == '__main__':
plus_one(None, add_to_away=False)
print(f"home: {home_score}, away: {away_score}")
plus_one(None, add_to_away=True)
print(f"home: {home_score}, away: {away_score}")
plus_one(None, add_to_away=True)
print(f"home: {home_score}, away: {away_score}")发布于 2019-10-17 03:50:38
虽然您可以按名称修改全局变量,但通常不应该这样做。
但是,如果您确实需要使这些变量全局化(而不是,例如,a dictionary或properties of a class中的条目),并且您真的不想编写多个更新函数,那么就有一个解决方案。
根据this answer,您可以修改globals返回的字典,它更新模块命名空间。
some_variable = None
def update(var, value):
globals()[var] = value
update('some_variable', 'some value')
print(some_variable) # Output: "some value"但如果这是可能的话,你应该避免这样做-有许多更好的方法来编写代码,这也为更令人兴奋的错误留下了空间。
away_score = 10
update('away_scoer', away_score + 1) # npote the typo
print(away_score) # It's still 10, but there was no error in Python.
update('update', print) # now updating prints instead
update('away_score', 11) # Prints "away_score 11"
print(away_score) # still 10
update('print', function_that_melts_your_computer) # probably a bad idea它也有更普通的缺点,比如让你的编辑器不开心,在某些地方破坏代码的完成。
https://stackoverflow.com/questions/58424551
复制相似问题