我试图制作一个有效的闹钟程序。它看起来比它看起来要复杂得多,但有理由说,我不会进入这里。但是,我遇到的问题是我在嵌套函数中创建了一个Alarm对象,但无论我做什么,我都无法在该函数之外访问该对象...我&#39 ;附上下面的删节代码。任何打电话给"检查"或"设置"在setAlarm之外永远找不到"警报"变量。请让我知道我做错了什么 - 我尝试将变量声明为全局变量,正如您所见,但它仍然无法解决...
谢谢!
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!\a\a\a\a\a\a\a\a\a\a"
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."
答案 0 :(得分:0)
您已将alarm
创建为本地变量。函数中定义的变量默认是局部的,而local本身就是它听起来的样子 - 它只存在于该函数内部。
你可以通过明确地将其作为全局变量来解决这个问题。这不是一个好主意,但它是最小的变化。只需将语句global alarm
添加到setAlarm
的顶部以及每个想要访问它的函数。
更好的解决方案是来自return alarm
的{{1}}。然后,在调用它的代码中,只存储返回值。例如:
setAlarm
现在,def setAlarm():
# your existing code
return alarm
def runAlarm():
alarm = setAlarm()
# your existing code
对同一个对象(也称为runAlarm
)有自己的本地引用,因此它可以使用它。