return an object of a different class

alex23 wuwei23 at gmail.com
Wed Feb 16 03:45:52 CET 2011


On Feb 16, 12:23 pm, s... 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...

Firstly, does MyNumbers _have_ to be a class? Or would a function
acting as a class factory be sufficient?

Otherwise, you can change the class of an object, even within its own
methods:

class MyNumbers(object):
  def __init__(self, n = 0):
    self.original_value = n
    self.__class__ = BigNumbers if n > 100 else SmallThing

class BigNumbers(MyNumbers):
  size = 'big'

class SmallNumbers(MyNumbers):
  size = 'small'

>>> from test import *
>>> s = MyNumbers(50)
>>> b = MyNumbers(200)
>>> type(s)
<class 'test.SmallNumbers'>
>>> s.size
'small'
>>> type(b)
<class 'test.BigNumbers'>
>>> b.size
'big'

Hope this helps.




More information about the Python-list mailing list