Returning something else from __init__ -- was Re: 2001 Enchancement Wishlist

Gareth McCaughan Gareth.McCaughan at pobox.com
Sat Dec 30 16:10:52 EST 2000


Pearu Peterson wrote:

> I see that many Python experts are against this proposal but anyway, I
> would like to support this idea with the following examples.
..
> That is, if imaginary part of a Complex number is zero, it's constructor
> would return Real instance:

What's wrong with

    class Complex:
      ...
    def make_complex(re,im):
      if im==0: return re
      return Complex(re,im)

and then

    a = make_complex(1,2)
    b = make_complex(1,0)

There's one thing that bothers me greatly about it:
that function ought to be less global. It would be
nice to be able to define class methods so that you
could say

    a = Complex.make(1,2)
    b = Complex.make(1,0)

I'm not sure whether the reason Python doesn't have
class methods is (1) Guido disapproves, or (2) they
wouldn't fit well with the way Python implements
instance methods. It's not clear to me how one could
fit class methods into Python now.

For now, the only feasible way to encapsulate these
things is in a module. So e.g. you could have a module
"complex" which defines a class "Complex" and a
factory function "make"; you'd probably say

    import complex

    a = complex.make(1,2)

and so on.

-- 
Gareth McCaughan  Gareth.McCaughan at pobox.com
sig under construc



More information about the Python-list mailing list