Calling constructor but not initializer
Steve Holden
steve at holdenweb.com
Fri Sep 21 10:47:02 EDT 2007
Steven D'Aprano wrote:
> I have a class that has a distinct "empty" state. In the empty state, it
> shouldn't have any data attributes, but it should still have methods.
>
> The analogy is with a list: an empty list still has methods like append()
> etc. but it has no "data", if by data you mean items in the list.
>
> I can construct an empty instance in the __new__ constructor, and I can
> initialize an non-empty instance in the __init__ initializer, but I can't
> think of any good way to stop __init__ from being called if the instance
> is empty. In pseudo-code, I want to do something like this:
>
> class Parrot(object):
> def __new__(cls, data):
> construct a new empty instance
> if data is None:
> return that empty instance
> else:
> call __init__ on the instance to populate it
> return the non-empty instance
>
>
> but of course __init__ is automatically called.
>
>
> Any suggestions for doing something like this?
>
>
Easy: use a method whose name is something other than __init__, then
don't bother to implement __init__. Note that __new__ shouldn't call
__init__ anyway, that's done by the instance creation mechanism.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Sorry, the dog ate my .sigline
More information about the Python-list
mailing list