On 02/16/2011 06:05 AM, Richard Thomas wrote:
On Feb 16, 2:23 am, s...@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.
--
Yves.                                                  http://www.SollerS.ca/
                                                        http://blog.zioup.org/
If you don't want to use a factory function I believe you can do this:

class MyNumber(object):
     def __new__(cls, n):
         if n<= 100:
             cls = SmallNumbers
         else:
             cls = BigNumbers
         return object.__new__(cls, n)
     ...

Chard.

Very beautiful code great alternative to factory method!
To memorize this pythonic way.

Regards
Karim
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to