Named integers and enums

Robert Brewer fumanchu at amor.org
Sun May 23 17:53:57 EDT 2004


Hallvard B Furuseth 
> Is this possible without too much code?
> 
>     class Named_int(object, int):
>         def __str__(self): return self.name
>         __repr__ = __str__
>         __slots__ = 'name'
>         # This does not work:
>         def __init__(self, name): self.name = name
>         # ...and it would be nice to freeze the name:
>         __setattr__ = __delattr__ = None
> 
>     x = Named_int(3, "foo")
>     print "%s = %d" % (x, x) # print "foo = 3"
> 
> Named_int(3, "foo") says "TypeError: an integer is required".
> I've tried other ways to specify both parameters, but no luck so far.
> BTW, this is Python2.2.  I don't know if we'll be able to upgrade
> anytime soon.

Because you are subclassing from an immutable, you need to override
__new__ (instead of, or in addition to, __init__):

>>> class named_int(int):
... 	def __new__(cls, val, name):
... 		self = int.__new__(cls, val)
... 		self.name = name
... 		return self
... 	
>>> x = named_int(3, "foo")
>>> x
3
>>> x.name
'foo'


Hope that helps!

Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list