Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #5038

Re: Custom string joining

From Terry Reedy <tjreedy@udel.edu>
Subject Re: Custom string joining
Date 2011-05-09 19:16 -0400
References <254518825.20110507153133@bitdefender.com> <BANLkTim-94Zfq1o0P5DnAKfywR=cTm2z9Q@mail.gmail.com> <4DC84B2E.9090209@free.fr> <354289288.20110509232527@bitdefender.com>
Newsgroups comp.lang.python
Message-ID <mailman.1362.1304982995.9059.python-list@python.org> (permalink)

Show all headers | View raw


On 5/9/2011 4:25 PM, Claudiu Popa wrote:

> I  already told in the first post that I've implemented __str__ function,
 > but it doesn't seems to be automatically called.

No, Python does not auto-coerce to strings (only between numbers).
You have to be explicit by calling str. Karim's statement "You just have 
to implement __str__() python special method for your "custom_objects". 
" means that str will then work.

> For instance, the following example won't work:
>
>>>> class a:
>          def __init__(self, i):
>                  self.i = i
>          def __str__(self):
>                  return "magic_function_{}".format(self.i)
>>>> t = a(0)
>>>> str(t)
> 'magic_function_0'
>>>> "".join([t])

print('\n'.join(str(ob) for ob in [a(0), a(1), a(None)]))

magic_function_0
magic_function_1
magic_function_None

-- 
Terry Jan Reedy

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Custom string joining Terry Reedy <tjreedy@udel.edu> - 2011-05-09 19:16 -0400

csiph-web