Concrete classes -- stylistic question

Jeff Epler jepler at unpythonic.net
Thu Oct 10 12:58:25 EDT 2002


On Thu, Oct 10, 2002 at 04:47:13PM +0000, Gerhard Häring wrote:
> Now who will come up with a neat example using metaclasses?

I'm using a function where a metaclass might serve the same purpose.  As
a bonus, __init__ lets (well, forces) you fill out values in "the standard order",
without keyword arguments.  An enhancement would let the subclass
specify the min # args and also take **kw.

(If you want to define other methods on your record, then don't use
MakeRecord, derive a class from Record explicitly.  For instance,
    class Polar:
        __slots__ = "r theta".split()

        def __mul__(self, other):
            if isinstance(self, Polar):
                return Polar(self.r * other.r,
                             math.fmod(self.theta + other.theta, 2*math.pi))
            else:
                return Polar(self.r * other, self.theta)
        # ...
)

---------------------------------------------------------------------------
import new

class Record(object):
    def __init__(self, *args):
        if len(args) != len(self.__slots__):
            raise TypeError, "%s takes exactly %s arguments (%s given)" % (
                self.__class__.__name__, len(self.__slots__, len(args)))
        for k, v in zip(self.__slots__, args):
            setattr(self, k, v)

def MakeRecord(name, slots):
    if isinstance(slots, str): slots = slots.split()
    return new.classobj(name, (Record,), {'__slots__': slots})

Polar = MakeRecord('Polar', "r theta")
---------------------------------------------------------------------------




More information about the Python-list mailing list