internal circular class references
James Stroud
jstroud at mbi.ucla.edu
Wed Dec 10 21:18:39 EST 2008
Ethan Furman wrote:
> Greetings List!
>
> I'm writing a wrapper to the datetime.date module to support having no
> date. Its intended use is to hold a date value from a dbf file, which
> can be empty.
>
> The class is functional at this point, but there is one thing I would
> like to change -- datetime.date.max and datetime.date.min are class
> attributes of datetime.date, and hold datetime.date values. At this
> point I have to have two lines outside the actual class definition to do
> the same thing, e.g.:
>
> <trimmed down class code>
> class NullDate(object):
> "adds null capable DateTime.Date constructs"
> __slots__ = ['_date']
> def __new__(cls, date='', month=0, day=0):
> nulldate = object.__new__(cls)
> nulldate._date = ""
> .
> .
> .
> return nulldate
> def __getattr__(self, name):
> if self:
> attribute = self._date.__getattribute__(name)
> return attribute
> else:
> if callable(dt.date.__dict__[name]):
> return int
> else:
> return 0
> def __nonzero__(self):
> if self._date:
> return True
> return False
> @classmethod
> def fromordinal(cls, number):
> if number:
> return cls(dt.date.fromordinal(number))
> else:
> return cls()
> NullDate.max = NullDate(dt.date.max)
> NullDate.min = NullDate(dt.date.min)
> </trimmed down class code>
>
> How can I move those last two lines into the class definition so that:
> 1) they are class attributes (not instance), and
> 2) they are NullDate type objects?
>
> ~ethan~
I resisted posting a similar question recently. After much
consideration, I realized that the inability to reference a class inside
its own definition must have been a deliberate design of the language.
So the short answer is you can't.
The way you have done it is best--its not a hack and is good style.
James
More information about the Python-list
mailing list