no return values for __init__ ??
Gordon McMillan
gmcm at hypernet.com
Thu Jan 6 14:16:28 EST 2000
Helge Hess writes:
> "Fred L. Drake, Jr." wrote:
> > Helge,
> > Yes: It doesn't make sense.
>
> Well, IMHO it does make sense, see below.
>
> > The job of the __init__() method is to
> > initialize the instance which has already been created.
>
> Why should we have this distinction ? I find it inconsistent to
> declare '__init__' to behave differently from other methods.
> *This* doesn't make sense to me.
>
> > There is no
> > way for a Python program to receive the return value.
>
> In the current interpreter not. That is what annoys me, since it
> is an completly articial limitation I don't understand. As
> mentioned it took only 5 minutes to 'correct' this limitation.
What happens when a derived class chains to the base class
__init__ and the base class __init__ changes "self"?
How about MI?
> > To implement the singleton pattern you appear to be
> > interested in,
> > try this:
>
> [singleton using function]
> > def C():
> > global _C_singleton
>
> This example covers only the most basic case and is a hack (eg
> how do I do 'o instanceof C' ?).
Make it obvious: rename the factory function to "getC()" and
rename "_C" to "C".
> The idea behind returning a
> value different from 'self' or 'None' is to customize the class
> based on the parameters.
If really you want to customize the class, you can assign to
the instance's __class__ attribute.
> eg:
> class ImmutableDictionaryClass: # this is abstract
> def __init__(self, keys, values):
> if len(keys) == 0:
> # always return the same empty dict to save memory
> if emptyImmutableDict is None:
> emptyImmutableDict = EmptyImmutableDict()
> return emptyImmutableDict
> elif len(keys) < 10:
> return SequentialDictionary(keys, values)
> else:
> return HashTableDictionary(keys, values)
>
> This is called a 'class-cluster' in Objective-C and has quite
> some advantages. Another useful application for clusters are
> string-objects (different classes for different char widths, eg
> Py8bitString, PyUnicodeString, ..)
And Fred's pattern is called a "factory" in a wide variety of
languages.
> The nice thing is that you only need a single (abstract) class to
> interact with. Defining a function like you did above seems
> unnecessarily hackish to me.
Hackishness is in the eye of the beholder.
> Notably removing the constraint in the interpreter doesn't affect
> existing Python code ! This is what I wonder about. The
> interpreter was apparently restricted intentionally in this
> regard and I wonder what lead to this decision.
Having "self" be a complete object when __init__ runs means
the language doesn't have to come up with a bunch of arcane
rules about default constructors, order in which base class
constructors are called etc.
It's what makes MI useful in Python (vs a feature that is nearly
impossible to use, as in some other languages).
- Gordon
More information about the Python-list
mailing list