skipping __init__ and using exploiting a class member instead
Ned Batchelder
ned at nedbatchelder.com
Sat Oct 19 21:13:53 EDT 2013
On 10/19/13 8:42 PM, Peter Cacioppi wrote:
> To be clear, my original post had a goof.
>
> So my original, de-goofed, idiom was
>
>
> class Foo (object) :
> _lazy = None
> def foo(self, x) :
> self._lazy = self._lazy or self.get_something(x)
> def get_something(self, x) :
> # doesn't really matter, so long as it returns truthy result
>
> and the new, improved idiom is
>
> class Foo (object) :
> def foo(self, x) :
> self._lazy = getattr(self, "_lazy", None) or self._get_something(x)
> def _get_something(self, x) :
> # doesn't really matter, so long as it returns truthy result
The use of getattr here seems unfortunate. Your original at least
didn't have that odd uncertainty about it. I'm not sure why you want to
avoid an __init__ method. Why not simply have one, and use it to
initialize your attributes, even if it is to None?
--Ned.
> I was laboring under some misconception that there was Python magic that allowed __init__ and only __init__ to add class attributes by setting their values. Good to know this piece of magic isn't part of Python, and thus lazy eval can be handled more cleanly than I originally thought.
>
> In other words, "Guido was here".
>
> Thanks again
>
More information about the Python-list
mailing list