str.join 与我的类型
是否有机会使用以下方式加入我的类型:
str.join()
我有我的类:
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))
我应该重写什么来执行这种代码:
','.join(Slice(1, 2), Slice(3, 4))
并得到如下结果:
'1:2,3:4'
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有什么。
Nothing.
我总是这样做:
但你也可以创建一个实用函数:
我认为这是有意的,而且通常是一件好事:Python 是严格类型的,这会在运行时消除一些愚蠢的错误。因此,不要尝试将
Slice
设为str
,而是将map
设为str
。如果您真的想搞点小技巧,请执行以下
操作:当我调用
str.__init__(self , 'test')
在构造函数中,我认为这通常是执行此操作的正确方法,因此这是一个好兆头,表明您不应该对str
进行子类化。但继续吧。搬起石头砸自己的脚。这很痛苦,但是以一种老式的每天学习新东西的方式:)I always just do this:
But you could also create a utility function:
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
astr
, but insteadmap
tostr
.If you really want to go hacky, do this:
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 subclassingstr
. But go ahead. Shoot yourself in the foot. It hurts, but in the good old-fashioned learn-something-new-a-day way :)只是为了好玩,我决定不使用任何迭代函数来调用 str(x)。所以这是我的解决方案
Just for the heck of it, I decided not to use any iterative function to call str(x). So here is my solution