Is there a way to modify datetime object in python?
In the function main I have
def main():
#...
def button_callback(button,a, byMouse,label):
#...
date = date - oneday
while(date.isoweekday()>5): date = date -oneday
#...
oneday = datetime.timedelta(1)
date = datetime.date.today()
python complains: local variable 'date' referenced before assignment, which is expected. In other parts of main() I pay attention not to assign but to modify, thus I have for example
def main():
# other part of main()
def clear_callback( button,byMouse,aaa):
a_cats.clear()
a_cats = set(["GT","GR"])
which python is happy about (it woudn't be if I set eg a_cats = a_cats.clear() ).
Is there a way to modify a datetime object without explicitly using "=", so that I can avoid using global variables ?
如果您使用Python 3.x,则可以将该变量声明为nonlocal
:
def main():
def button_callback(button,a, byMouse,label):
nonlocal date # <--------------
date = date - oneday
...
oneday = datetime.timedelta(1)
date = datetime.date.today()
datetime
object is immutable. The only way to change date
is to bind it to a new datetime
object.
To assign to outer-scope variable, you could use nonlocal
in Python 3 as @falsetru suggested or emulate it using a list or a custom object in Python 2:
def button_callback(self, *args):
self.date -= DAY
See What limitations have closures in Python compared to language X closures?
链接地址: http://www.djcxy.com/p/51258.html上一篇: 变量如何在lambda函数中工作?