Named integers and enums
Peter Otten
__peter__ at web.de
Sun May 23 17:53:43 EDT 2004
Hallvard B Furuseth wrote:
> 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"
You need __new__() instead of __init__():
<namedint.py>
class Int(int):
_all = {}
def __new__(cls, name, value):
try:
return cls._all[value]
except KeyError:
cls._all[value] = self = int.__new__(cls, value)
self.name = name
return self
def __str__(self):
return self.name
def __repr__(self):
return "%s:%s" % (self, int.__str__(self))
</namedint.py>
>>> from namedint import *
>>> debug, info, warn = map(Int, "DEBUG INFO WARN".split(), range(3))
>>> debug
DEBUG:0
Instances are cached in _all and thus only created once per value:
>>> Int("too late", 0)
DEBUG:0
>>> debug < info
1
>>> info + warn
3
>>>
Addition etc. will continue to return ints:
>>> info + warn
3
Peter
More information about the Python-list
mailing list