return an object of a different class

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Feb 16 14:20:39 CET 2011


On Tue, 15 Feb 2011 19:23:39 -0700, spam wrote:

> How can I do something like this in python:
> 
> #!/usr/bin/python3.1
> 
> class MyNumbers:
>    def __init__(self, n):
>      self.original_value = n
>      if n <= 100:
>        self = SmallNumers(self)
>      else:
>        self = BigNumbers(self)

(1) self is just a local variable, it isn't privileged in any way. 
Assigning to the name "self" doesn't magically change the instance, so 
that can't work.

(2) By the time the __init__ method is called, the instance has been 
created. __init__ is the initializer, you need the constructor. Something 
like this:


# Untested.
class MyNumbers:
    def __new__(cls, n):
        if n <= 100:
            instance = SmallNumbers(n)
        else:
            instance = BigNumbers(n)
        return instance



-- 
Steven



More information about the Python-list mailing list