guids and super(str)

Andrew Bennetts andrew-pythonlist at puzzling.org
Thu May 1 23:02:44 EDT 2003


On Fri, May 02, 2003 at 03:07:05AM +0000, Clark C. Evans wrote:
> Ok.  I'm trying to make a GUID object, so that, when I nmake a new
> one, it generates the guid for me.   Two questions.  First, is the
> method below an "ok" way to make a guid?   And second, why doesn't
> this override of str work propertly, ie, I'd like the string value
> to be the generated guid...
> 
> class Identifier(str):
>     macaddr = os.popen('/sbin/ifconfig -a | grep ether','r').readline()
>     macaddr = "".join(macaddr.split()[1].split(":")).upper()
>     def __init__(self):
>         val = hex(long(time.time()*1000000))[2:]
>         val = "%s:%s" % (macaddr,val)
>         str.__init__(self,val)
> 
> x = Identifier()
> 
> but x is always blank on Python 2.2.2, even though val isn't.

When subclassing a builtin immutable type (such as str, tuple or the
numeric types), you need to override __new__ to change the value.

By the time __init__ is called, the immutable object has already been
allocated, so it's too late to change its value.

-Andrew.






More information about the Python-list mailing list