__name__ on new-style classes
Gonçalo Rodrigues
op73418 at mail.telepac.pt
Mon Apr 1 09:03:41 EST 2002
On Mon, 01 Apr 2002 02:35:47 GMT, Guido van Rossum <guido at python.org>
wrote:
>"Gonçalo Rodrigues" wrote:
>>
>> One can change the name of a classic class but not of a new-style one
>> (see below for example). Is this a bug or a feature, and if the latter
>> is there any reason for the change?
>
>It's a feature. The reason for the change is that I've never seen an
>example of a use for it (as opposed to changing an instance's __class__).
>If you have one, let us know.
>
>--Guido van Rossum (home page: http://www.python.org/~guido/)
I bumped into this "feature" a few days ago trying to understand
metaclasses in Python. And to understand them there is nothing better
than actually coding one, so I'll explain my problem/solution and let
you judge if this is a good use case for having a writable __name__.
My problem is modelling finite arithmetic in Python. Here by finite
arithmetic I mean all the quotients of the integer ring Z. There is a
countable number of them, one for each n > 1 (n=0 is Z and n=1 is the
trivial ring {0}. If n is negative then it is the same as -n). If n is
prime then we actually have a field.
The obvious way (to me, that is) to do this is to let each finite ring
Z_n be a class, inheriting from int. Since there are an infinite number
of these we have to have a metaclass, call it Field, that has as
intances the Z_n rings, e.g. Z_n would be Field(n). The skeleton of this
metaclass would be something like:
class Field(type):
"""The Finite Field metaclass."""
def __new__(cls, n):
if isinstance(n, int) and n > 1:
#The template class.
class Z(int):
pass
#Generate proper name for the instance class, e.g. "Z_n"
Z.__name__ = "Z_%d" % n
#Return class.
return Z
else:
raise TypeError, "%s is not an integer > 1." % str(n)
If I cant write to __name__ then all the instances will have the same
name... Not A Good Thing, IMHO.
All the best,
Gonçalo Rodrigues
More information about the Python-list
mailing list