return an object of a different class

Jean-Michel Pichavant jeanmichel at sequans.com
Thu Feb 17 05:49:07 EST 2011


spam at uce.gov 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)
>
> class SmallNumbers:
>   def __init__(self, n):
>     self.size = 'small'
>
> class BigNumbers:
>   def __init__(self, n):
>     self.size = 'big'
>
> t = MyNumbers(200)
>
>
> When I do type(t) it says MyNumbers, while I'd want it to be 
> BigNumbers, because BigNumbers and SmallNumbers will have different 
> methods etc...
>
> Do I need to use metaclasses?
>
> Thanks.
You simply don't return inconsistent types with a return statement. This 
is a general rule in programming that has probably exceptions but 
regarding what you're saying, you clearly don't want to do that.

Immagine the following code:

oNumber = MyNumbers(random.int(100)) # note that oNumber is not a 
MyNumbers instance... quite confusing don't you think ?
oNumber. ... wait a minute, which methods am I allowed to call ??? 
SmallNumbers adn BigNumbers have differents methods.

Some rules to follow, until you get some experience with python:
* use consistent types for method parameters.
* use consistent types for returned values.
* a class constructor should return an instance of that very same class.

JM



More information about the Python-list mailing list