Python中调用函数后如何正确获取并使用变量sets
解决Python函数内外变量同步问题
你遇到的问题核心是:函数内部定义的sets是局部变量,和全局作用域的sets是两个独立的变量,所以函数内的赋值不会改变全局的sets值。下面是三种可行的解决方法:
方法一:使用global声明全局变量
在函数开头声明要使用全局的sets,这样函数内的赋值会直接作用于全局变量:
sets = 0 def search_str(monatsabrechnung, d1): global sets # 声明使用全局作用域的sets with open(monatsabrechnung, 'r') as file: content = file.read() # 确保lastDay、heute、ja是已定义的变量 if lastDay == heute and ja == 1: sets = 1 else: pass search_str(monatsabrechnung, d1) print(sets)
方法二:让函数返回值(推荐)
这种方式更符合Python的函数设计规范,避免全局变量带来的副作用:
sets = 0 def search_str(monatsabrechnung, d1): with open(monatsabrechnung, 'r') as file: content = file.read() if lastDay == heute and ja == 1: return 1 else: return 0 # 条件不满足时返回初始值,也可以返回传入的原有值 # 调用函数时接收返回值更新sets sets = search_str(monatsabrechnung, d1) print(sets)
如果需要保留sets的原有值(条件不满足时不改变),可以把sets作为参数传入函数:
def search_str(monatsabrechnung, d1, current_sets): with open(monatsabrechnung, 'r') as file: content = file.read() if lastDay == heute and ja == 1: return 1 else: return current_sets sets = 0 sets = search_str(monatsabrechnung, d1, sets) print(sets)
方法三:用可变对象包装变量
利用列表等可变类型的特性,函数内部修改可变对象的元素会同步到外部:
sets = [0] # 用列表包装初始值 def search_str(monatsabrechnung, d1, sets_list): with open(monatsabrechnung, 'r') as file: content = file.read() if lastDay == heute and ja == 1: sets_list[0] = 1 else: pass search_str(monatsabrechnung, d1, sets) print(sets[0])
内容的提问来源于stack exchange,提问作者Sn0w3y
相关产品推荐
相关产品推荐

