Using metaclasses to play with decorators.

David MacQuigg dmq at gain.com
Fri Jun 18 01:04:25 EDT 2004


On Thu, 17 Jun 2004 08:05:03 -0500, Jeff Epler <jepler at unpythonic.net>
wrote:

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

I just read Alex Martelli's 4 pages on metaclasses in "Python in a
Nutshell", and I'm finally starting to understand this topic.  Thanks
to you and Michele Simionato for catching my misunderstanding on the
use of __new__.

I've also corrected the one-page explanation of metaclasses in my OOP
chapter.  I had decided earlier to take this out of the chapter, but
now I think I will leave it in.  Metaclasses have an advantage over
factory functions that makes learning at least the basics worth while.
That is my current understanding, anyway.  I'm still learning.

-- Dave

>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




More information about the Python-list mailing list