好的,这是我的代码:
tick = 1
week = 1
month = 1
year = 1
def new_week(week, tick):
week = week + 1
tick = tick + 1
if tick == 4:
new_month()
tick = 1
new_week(week, tick)
print week, tick
new_week(week, tick)
print week, tick
无论后来多少次我告诉它运行new_week()函数并打印周'周的值。并且' tick',它总是为两者打印1 ...为什么它忽略了'周=周+ 1' ' tick' ??
我正在运行Python 2.7 btw
答案 0 :(得分:3)
全局名称week
和tick
被函数参数的名称所遮蔽。
您需要删除这些参数(因为它们是不必要的),并且还将week
和tick
声明为函数内的全局(这将允许您修改它们的值):
tick = 1
week = 1
month = 1
year = 1
def new_week():
global week, tick # Declare that week and tick are global
week = week + 1 # Modify the value of the global name week
tick = tick + 1 # Modify the value of the global name tick
if tick == 4:
new_month()
tick = 1
new_week()
print week, tick
new_week()
print week, tick
输出:
2 2
3 3
但是请注意,许多Python程序员认为使用全局声明的函数非常不优雅。更加pythonic的方法是使用值的字典,并有一个函数来递增它们。
以下是一个非常简单的示例,可以帮助您入门:
dct = {
'tick': 1,
'week': 1,
'month': 1,
'year': 1
}
def increment(key):
dct[key] += 1
increment('week')
print dct['week']
increment('tick')
print dct['tick']
输出:
2
2
答案 1 :(得分:1)
这是关于范围的。
# here you are setting your variables, there scope is essentially global
tick = 1
week = 1
month = 1
year = 1
# we enter the function definition
def new_week(week, tick):
# you passed in your variables, and increment them
# however, they are only changed within the local scope of this function
# and since you didn't RETURN them as shown below, you are leaving the
# global variables from above, unchanged
week = week + 1
tick = tick + 1
if tick == 4:
new_month()
tick = 1
# when you print them out below, you are printing the unchanged globally scoped variables
new_week(week, tick)
print week, tick
new_week(week, tick)
print week, tick
为了获得理想的结果,您可以这样做:
tick = 1
week = 1
month = 1
year = 1
def new_week(week, tick):
week += 1
tick += 1
if tick == 4:
new_month()
tick = 1
return (week, tick) #### return the variables
>>> week, tick = new_week(week, tick) ### capture the returned variables
>>> print week, tick
(2, 2)
每次致电tick
时,week
和new_week
都会继续增加。显然,tick
一旦达到4就会重置。如果您想将变量存储在list
或dict
中,那么您可以执行以下操作:
使用dict
:
vars = {'tick': 1, 'week': 1, 'month': 1, 'year': 1}
现在改变了函数处理数据的方式:
def new_week(lst=None):
if lst:
for key in lst:
vars[key] += 1
if vars['tick'] == 4:
new_month()
vars['tick'] = 1
>>> new_week(['week', 'tick'])
>>> print vars['week'], vars['tick']
2 2
在此处阅读范围:
https://www.inkling.com/read/learning-python-mark-lutz-4th/chapter-17/python-scope-basics
http://www.python-course.eu/python3_global_vs_local_variables.php
答案 2 :(得分:1)
首先,week = week + 1
只是将(本地)名称week
重新绑定为新值;它不会影响调用范围中的变量。但是,由于int
是不可变的,因此即使week+=1
也不会影响调用范围;它仍然只是更新函数本地week
变量。
一种选择是使用dict
而不是单个变量。由于dict
是一个可变对象,因此您可以将引用传递给dict
作为参数,并且对该对象的更改将在调用范围中可见。
times = { 'tick': 1, 'week': 1, 'month': 1, 'year': 1}
def new_week(t):
t['week'] += 1
t['tick'] += 1
if t['tick'] == 4:
new_month(t)
t['tick'] = 1
new_week(times)