Calling constructor but not initializer

Hrvoje Niksic hniksic at xemacs.org
Fri Sep 21 16:53:37 CEST 2007


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

> 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

Suggestion 1: since you "construct a new empty instance" in both
cases, simply move the entire logic to __init__.

Suggestion 2: name your initialization method something other than
__init__ and the
calling-type-object-automatically-calls-__init__-after-__new__ simply
disappears.

Can you specify the way you'd like to instantiate the class?



More information about the Python-list mailing list