I might be blind, but I really can't see why this class fails with:
AttributeError: NextSunday instance has no attribute 'trigger'
from datetime import datetime
from datetime import time
from datetime import timedelta
class NextSunday():
def __init__(self, trigger=None):
"""
Get date of, and number of days until, next Sunday.
Arguments:
- `trigger`: Add an extra week if less than trigger number of days.
"""
self.str = u'%s (%s days)' % (self.date().date(), self.no_days())
self.trigger = trigger
def __unicode__(self):
return self.str
def __str__(self):
return unicode(self).encode('utf-8')
def __repr__(self):
return '<Next Sunday: ' + self.str + '>'
def no_days(self):
"""Get date of next sunday. """
days = None
for i in range(7):
dt = datetime.now() + timedelta(days=i)
if dt.weekday() == 6:
days = i
# Add another week if there are less days left then trigger
if self.trigger:
if days < self.trigger:
days += 7
return days
def date(self):
# The datetime obj contains the next sunday, but also the current time
dt_of_next_sun = datetime.now() + timedelta(days=self.no_days())
# Get the whole day
date_of_next_sun = datetime.combine(dt_of_next_sun.date(),
time(23, 59))
return date_of_next_sun
mgilson
312k70 gold badges657 silver badges723 bronze badges
asked Nov 1, 2012 at 20:47
Niclas Nilsson
5,9114 gold badges34 silver badges45 bronze badges
-
1eliminiate the unnecessary lines, till you locate the root of the problem.Karoly Horvath– Karoly Horvath2012年11月01日 20:54:19 +00:00Commented Nov 1, 2012 at 20:54
-
1The full stacktrace would identify the originating line.Marcin– Marcin2012年11月01日 20:57:34 +00:00Commented Nov 1, 2012 at 20:57
-
1This is why I developed the habit of always setting instance variables first, at the top of the initializer, before calling any methods.Keith– Keith2012年11月01日 22:24:56 +00:00Commented Nov 1, 2012 at 22:24
1 Answer 1
You need to switch these
self.str = u'%s (%s days)' % (self.date().date(), self.no_days())
self.trigger = trigger
like this
self.trigger = trigger
self.str = u'%s (%s days)' % (self.date().date(), self.no_days())
because otherwise the no_days method is called before the self.trigger attribute is created. This is bad because the no_days method tries to read the value of the self.trigger attribute:
if self.trigger:
if days < self.trigger:
answered Nov 1, 2012 at 20:50
Lauritz V. Thaulow
51.3k13 gold badges76 silver badges94 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Niclas Nilsson
Oh, that was interesting. It solved the problem (marks the question as solved soon). But why is this? I can't see it.
Karoly Horvath
you call
no_days before trigger is set.Lauritz V. Thaulow
@Niclas I've updated my answer with what is hopefully a more thorough explanation.
Niclas Nilsson
@lazyr Oh, that should be obvious. But I havn't encountered this before so I did'nt think about it. Thanks alot!
lang-py