return an object of a different class

Ben Finney ben+python at benfinney.id.au
Tue Feb 15 21:35:27 EST 2011


spam at uce.gov writes:

> 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)

A class defines a type of object. If you don't actually want instances
of that class, then you don't really want a class.

> 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?

You could. Or you could simply use a factory function::

    def make_number(value):
        if value <= 100:
            result = SmallNumbers(value)
        else:
            result = BigNumbers(value)
        result.original_value = value
        return result

    t = make_number(200)

-- 
 \              “Programs must be written for people to read, and only |
  `\        incidentally for machines to execute.” —Abelson & Sussman, |
_o__)              _Structure and Interpretation of Computer Programs_ |
Ben Finney



More information about the Python-list mailing list