This coding style bad practise?
Martin P. Hellwig
mhellwig at xs4all.nl
Wed May 3 16:36:49 EDT 2006
Hi all,
I created a class which creates a relative unique id string, now my
program just works fine and as expected but somehow I get the feeling
that I misused the __repr__ since I guess people expect to 'execute' a
function in an instance instead of using it's representation string of
the instance itself, could you elaborate whether you find this bad
practice and if yes what would have been a better way to do it?
TIA
----- script -----
> import string
> import time
>
> class IDGenerator(object):
> """(serverID,subversion_length)
> Create an ID from the server name, datetimestamp and version number.
> Calling the instance returns the ID using the __repr__ class function
>
> Example usage:
> >>> id = idgen('01',4)
> >>> id
> 01_20060424_151903_1
> >>> id
> 01_20060424_151905_2
> >>> id
> 01_20060424_151905_3
> >>> id
> 01_20060424_151906_4
> >>> id
> 01_20060424_151907_1
> >>>
> >>> id = idgen(04,100)
> >>> id
> 4_20060424_152043_001
>
> """
>
> def __init__(self,serverID,subversion_length):
> self.ID = str(serverID)
> self.length = int(subversion_length)
> fill_length = len(str(self.length))
>
> def fill(number):
> return(string.zfill(number,fill_length))
> self.fill = fill
>
>
> def __repr__(self):
> # If the subversion length has been reached or the generator has not
> # been defined, (re)define it, otherwise return the next value of the
> # subversion.
> try:
> return_value = self.range_gen.next()
>
> except:
> self.range_gen = ( number for number in range(1,self.length+1) )
> return_value = self.range_gen.next()
>
> # Create the version stamp.
> return_value = self.ID +\
> time.strftime("_%Y%m%d_%H%M%S_",time.gmtime())+\
> self.fill(return_value)
>
> # And return it.
> return(return_value)
----- script -----
--
mph
More information about the Python-list
mailing list