Is there opportunity to join my types using:
str.join()
I have my class:
class Slice(object):
def __init__(self, start, end):
self.__start = start
self.__end = end
def __str__(self):
return '{0}:{1}'.format(self.__start, self.__end)
def __repr__(self):
return "'{}'".format(str(self))
What should i override to perform this kind of code:
','.join(Slice(1, 2), Slice(3, 4))
And get a result like this:
'1:2,3:4'
没有。
','.join(str(x) for x in (Slice(1, 2), Slice(3, 4)))
I always just do this:
','.join(map(str, (Slice(1, 2), Slice(3, 4)))
But you could also create a utility function:
def strseq(*args):
for arg in args:
yield str(arg)
','.join(strseq(Slice(1, 2), Slice(3, 4)))
I think this is intentional and generally a good thing: Python is strictly typed and that will shake out some silly bugs at run-time. So don't try to make the Slice
a str
, but instead map
to str
.
If you really want to go hacky, do this:
class Slice(str):
def __init__(self, start, end):
self.__start = start
self.__end = end
str.__init__('{0}:{1}'.format(self.__start, self.__end))
I keep getting an error "TypeError: str() takes at most 1 argument (2 given)" when I call str.__init__(self, 'test')
in the constructor, which would normally be the correct way to do this, I think, so this is a good sign that you are not supposed to be subclassing str
. But go ahead. Shoot yourself in the foot. It hurts, but in the good old-fashioned learn-something-new-a-day way :)
Just for the heck of it, I decided not to use any iterative function to call str(x). So here is my solution
x=(Slice(1, 2), Slice(3, 4))
','.join(['%s']*len(x)) % x
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.