print - parameters ?
Peter Abel
PeterAbel at gmx.net
Tue Oct 5 14:03:46 EDT 2004
Helmut Jarausch <jarausch at igpm.rwth-aachen.de> wrote in message news:<2sf68hF1jj1mlU1 at uni-berlin.de>...
> Hi,
> sorry for this probably very simple question.
>
> How can I build a parameter list for 'print' ?
>
> Background:
> I'd like to write a function like
>
> def myprint(Msg,*Args) :
> print (Msg,)+Args
>
> when called as
>
> myprint(MyMsg,x)
>
> it should be equivalent to
>
> print MyMsg,x
>
> but, e.g.
>
> class ABC :
> def __str__(self) :
> return "ABC-class"
>
> x=ABC()
>
> myprint('this is',x)
>
> gives
>
> ('this is', <__main__.ABC instance at 0x4084fc8c>)
>
> instead of
>
> this is ABC-class
>
> What am I missing (what sort of thing is the parameter list of print) ?
> Many thanks for a hint,
>
>
> Helmut Jarausch
>
> Lehrstuhl fuer Numerische Mathematik
> RWTH - Aachen University
> D 52056 Aachen, Germany
As Alex pointed out there is a tiny difference
between __repr__ and __str__ but with an eminent effect
see the following examples:
case 1:
-------
>>> class ABC:
... def __str__(self):
... return "ABC-class"
...
>>> x=ABC()
>>> x
<__main__.ABC instance at 0x00DFA640>
>>> '%s' % x
'ABC-class'
>>> '%r' % x
'<__main__.ABC instance at 0x00DFA640>'
case 2:
-------
>>> class ABC:
... def __repr__(self):
... return "ABC-class"
... def __str__(self):
... return "ABC-class"
...
>>> x=ABC()
>>> x
ABC-class
>>> '%r' % x
'ABC-class'
>>>
So for both cases the following function works:
>>> def myprint(Msg,*Args) :
... format=''.join(['%s']*(len(Args)+1))
... print format % tuple([Msg]+map(str,Args))
...
>>> class ABC:
... def __str__(self):
... return "ABC-class"
...
>>> x=ABC()
>>> myprint('this is ',x)
this is ABC-class
>>> class ABC:
... def __repr__(self):
... return "ABC-class"
... def __str__(self):
... return "ABC-class"
...
>>> x=ABC()
>>> myprint('this is ',x)
this is ABC-class
>>>
BTW the need of the statement
... print format % tuple([Msg]+map(str,Args))
was new for me too.
Regards
Peter
More information about the Python-list
mailing list