[Tutor] Convert values in a list back and forth from ints and time

ALAN GAULD alan.gauld at btinternet.com
Tue Jan 6 20:40:13 CET 2009


> > If you always convert the values back to strings then you could
> > just hold onto the original strings by storing them in a (str, val) tuple.
> > If you do calculations and modify anmy of them then convert the
> > value/string there and then and modify the tuple. You could even
> > make it a class with the convertion fiunctions being methods.


> This is too complex and the speed is good enough for 2000 lines in the
> file. however...


Fair enough, I suspected as much.

> I am doing this to learn about python and programming. So I am
> interested how this class would look like. Could you give an example
> or point me in the right direction how I can figure it out for myself?


You just nered to define a class that can take a string and has 
methods to return the value. You could store both string and value
as attributes and have two methods to convert between them. Here 
is a very simple example:

>>> class Value:
...    def __init__(self, vs = ""):
...       self.vs = vs
...       self.v = self.asInt()
...    def asInt(self):
...       try: self.v = int(self.vs)
...       except: self.v = None
...       return self.v
...    def asString(self):
...        vs = str(self.vs)
...        return self.vs
...    def setStringValue(self, s):
...        self.vs = s
...        self.asInt()
...    def setIntValue(self, i):
...        self.v = int(i)
...        self.vs = str(self.v)
...     
>>> v = Value('42')
>>> print v.v, v.vs
42 42
>>> v.setStringValue('66')
>>> print v.v, v.vs
66 66
>>> v.setIntValue(7)
>>> print v.v, v.vs
7 7
>>> 

HTH,

Alan G.


More information about the Tutor mailing list