我正在努力制作一个实际上是闹钟的程序。这比看起来更复杂,但这是有原因的,我不会在这里详述。不过,我遇到的问题是,我在嵌套函数中创建了一个Alarm对象,但无论我做什么,我都无法在该函数之外访问该对象。。。我在下面附上了代码摘要。setAlarm之外的任何对"check"或"set"等的调用都永远找不到"alarm"变量。请告诉我我做错了什么——正如你所看到的,我试图将变量声明为全局变量,但仍然没有成功。。。
谢谢!
class Alarm(threading.Thread):
def __init__(self, datetime, grace, close):
super(Alarm, self).__init__()
self.datetime = datetime
self.grace = grace
self.close = close
self.keep_running = True
def run(self):
try:
while self.keep_running:
now = datetime.datetime.now()
if now > self.datetime + datetime.timedelta(minutes=self.grace):
print "Oh no! It's %02d:%02d, which is %d minutes past your alarm time of %02d:%02d!" % (now.hour,now.minute,self.grace,self.datetime.hour,self.datetime.minute)
print "ALARM NOW!aaaaaaaaaa"
break
time.sleep(10)
except:
return
def just_die(self):
self.keep_running = False
def setAlarm():
print "What time would you like to set the alarm for? (in 00:00 military time please)"
wakeup = raw_input()
wakeuphour = int(wakeup[:2])
wakeupmin = int(wakeup[3:])
now = datetime.datetime.now()
if now.hour > wakeuphour or (now.hour == wakeuphour and now.minute > wakeupmin):
alarmday = now + datetime.timedelta(days=1)
alarmtime = datetime.datetime(alarmday.year,alarmday.month,alarmday.day,wakeuphour,wakeupmin)
else:
alarmtime = datetime.datetime(now.year,now.month,now.day,wakeuphour,wakeupmin)
close = 15
grace = 5
alarm = Alarm(alarmtime, grace, close)
if alarmtime.day != now.day:
print "Your alarm is set for %02d:%02d tomorrow." % (alarmtime.hour,alarmtime.minute)
else:
print "Your alarm is set for %02d:%02d today." % (alarmtime.hour, alarmtime.minute)
def runAlarm():
setAlarm()
alarm.start()
while True:
print "You can say 'stop', 'check', 'change', 'set', or 'quit'"
text = str(raw_input())
if text == "stop":
if alarm != 0:
alarm.just_die()
alarm = 0
print "Okay, I've cancelled the alarm."
else:
print "There was no alarm to stop..."
elif text == "check":
if alarm == 0:
print "Sorry, you don't have any alarm set. To create an alarm, type 'set'"
else:
pass
elif text == "change":
pass
elif text == "set":
alarm = 0
setAlarm()
alarm.start()
elif text == "quit":
print "Sure thing. Bye bye!"
break
else:
print "Sorry, I didn't understand that. Please try again."
您已经将alarm
创建为局部变量。默认情况下,函数中定义的变量是局部的,而局部的意思正是它听起来的样子——它只存在于函数内部。
您可以通过显式地将其设置为全局变量来修复此问题。这不是一个好主意,但这是最小的变化。只需将语句global alarm
添加到setAlarm
和每个想要访问它的函数的顶部
一个更好的解决方案是从setAlarm
到return alarm
。然后,在调用它的代码中,只存储返回值。例如:
def setAlarm():
# your existing code
return alarm
def runAlarm():
alarm = setAlarm()
# your existing code
现在,runAlarm
对同一对象(也称为alarm
)有自己的本地引用,因此它可以使用它。