[Tutor] re

Andre Engels andreengels at gmail.com
Wed Jan 7 11:09:51 CET 2009

On Wed, Jan 7, 2009 at 10:57 AM, prasad rao <prasadaraon50 at gmail.com> wrote:
> Hello
> I am trying to get a value as integer and a string.
>>>> class Value:
>       def __init__(self,inte='',stri=''):
>           self.inte=inte
>           self.stri=stri
>       def setvalue(self,inte='',stri=''):
>          self.stri=str(self.inte)
>          self.inte=int(self.stri)
>>>> v=Value(45)
>>>> print v.stri
>>>> v.inte
> 45
>>>> v.stri
> ''
>>>> c=Value('36')
>>>> c.stri
> ''
> But it is not converting.How can I do it?
> Prasad

Let's take a step back, and see what is happening here.

>>>> v=Value(45)

This means that you create a Value object. If you create an object,
its __init__ is called. What does that ini look like?

def __init__(self,inte='',stri='')

We disregard the 'self' for now, and look at the other arguments. The
_first_ argument of your function will be mapped to inte, the second
to stri. In this case you have only one argument, so this argument
(45) will be mapped to inte, and stri will take its default value
(which is '')

>           self.inte=inte
>           self.stri=stri

So after this, self.inte will be set to inte (that is 45), and
self.stri to stri (that is ''). Which indeed is exactly what you get
when you look up v.inte and v.stri.

>>>> c=Value('36')

If we go through the analysis above, you will find that after this
c.inte = '36'
c.stri = ''

What would you _want_ to do? I think what you want is the following:
you give a single argument, which can either be an integer or a string
representing an integer, and the local variables inte and string
should then give the integer and string representation of that
argument. This can be done in the following way:

class Value:
    def __init__(self,val):  # I do not add a default value for val,
because I will always call Value(somevalue), not
        self.inte = int(val) # Whether val is a string or an integer,
this will be its integer representation
        self.stri = str(val) # similar

(when typing this in you can of course do without the #s and whatever
I have written after that)

André Engels, andreengels at gmail.com

More information about the Tutor mailing list