Changing the repr() of a class?
Alex Martelli
aleax at aleax.it
Thu Apr 18 18:58:11 EDT 2002
Lulu of the Lotus-Eaters wrote:
> Alex Martelli <aleax at aleax.it> wrote previously:
> |class FunkyReprMeta(type):
> | def __repr__(cls):
> | return "My wonderful class %s" % cls.__name__
> |class FunkyReprObject:
> | __metaclass__ = FunkyReprMeta
> |class C(FunkyReprObject):
> | "whatever you want here"
>
> I don't really understand what a metaclass buys you here. I think I
> might be missing something important, since Alex proposes it.
Thanks for the compliment, but you're only missing *the whole point*,
it seems to me.
> However, it appears that one could simply define the __repr__ method in
> the regular class FunkyReprObject, ignore metaclasses altogether, and
> wind up with the same results.
Obviously not: when you define a special method in a class, you control
operation of the *instances* of the class, NOT of the class object itself.
When you want to control operations on the class object itself, you must
then obviously define special methods in the class's class -- i.e., the
metaclass. That's the main reason for custom metaclasses to exist at all:
the special methods that they define control operations on the classes that
instantiate them (just as a key reason for a class to exist is to define
special methods to control operation on the class's instances).
Alex
More information about the Python-list
mailing list