Using metaclasses to play with decorators.

Jeff Epler jepler at unpythonic.net
Thu Jun 17 09:05:03 EDT 2004


On Wed, Jun 16, 2004 at 04:18:53AM -0700, David MacQuigg wrote:
> I haven't given this much thought, but it occurred to me that making
> the __new__ function work in an ordinary class ( not just a metaclass
> ) would avoid the need for metaclasses in simple cases like my
> example.  [...]

__new__ does work in an "ordinary class"!  It just does something
different than what you want.  Here's a small "rational number" class
where Rational(x, y) returns an int if x/y is an integer, or a Rational
instance otherwise.

class Rational(object):
    def __init__(self, num, den=1):
        self.num = num
        self.den = den

    def __new__(self, num, den=1):
        if num % den == 0:
            return int(num)
        else:
            return object.__new__(Rational)

    def __str__(self): return "%d/%d" % (self.num, self.den)

# Example
r, s = Rational(6, 3), Rational(6, 4)
print r, type(r)  # It's an int
print s, type(s)  # It's a Rational

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040617/f9fad86e/attachment.sig>


More information about the Python-list mailing list