在Python中,我可以这样做:
>>> list = ['a', 'b', 'c']
>>> ', '.join(list)
'a, b, c'
Run Code Online (Sandbox Code Playgroud)
当我有一个对象列表时,有没有简单的方法来做同样的事情?
>>> class Obj:
... def __str__(self):
... return 'name'
...
>>> list = [Obj(), Obj(), Obj()]
>>> ', '.join(list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, instance found
Run Code Online (Sandbox Code Playgroud)
或者我是否必须求助于for循环?
任何人都可以向我解释一下toString()在Object课堂上定义的方法的概念吗?它是如何使用的,它的目的是什么?
在Java中,如果我调用List.toString(),它将自动调用List内每个对象的toString()方法.例如,如果我的列表包含对象o1,o2和o3,则list.toString()将如下所示:
"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"
Run Code Online (Sandbox Code Playgroud)
有没有办法在Python中获得类似的行为?我在我的类中实现了__str __()方法,但是当我打印出一个对象列表时,使用:
print 'my list is %s'%(list)
Run Code Online (Sandbox Code Playgroud)
它看起来像这样:
[<__main__.cell instance at 0x2a955e95f0>, <__main__.cell instance at 0x2a955e9638>, <__main__.cell instance at 0x2a955e9680>]
Run Code Online (Sandbox Code Playgroud)
如何让python自动为列表中的每个元素调用我的__str__(或者dict为此)?
我知道,str()方法的目的是返回一个对象的字符串表示,所以我想测试如果我强迫它做其他事情会发生什么.
我创建了一个类和一个对象:
class MyClass(object):
def __str__(self, a=2, b=3):
return a + b
mc = MyClass()
Run Code Online (Sandbox Code Playgroud)
我打电话的时候:
print(str(mc))
Run Code Online (Sandbox Code Playgroud)
口译员抱怨说:
TypeError: __str__ returned non-string (type int)
Run Code Online (Sandbox Code Playgroud)
这是完全可以理解的,因为str()方法试图返回int.
但如果我尝试:
print(mc.__str__())
Run Code Online (Sandbox Code Playgroud)
我得到输出:5.
那么为什么解释器允许我在__str__直接调用时返回int ,而不是当我使用str(mc)时 - 正如我所理解的那样 - 也被评估为mc.__str__().
如果我尝试打印作为列表的类变量,我会得到一个Python对象.(这些是我在stackoverflow上找到的例子).
class Contacts:
all_contacts = []
def __init__(self, name, email):
self.name = name
self.email = email
Contacts.all_contacts.append(self)
def __str__(self):
return '%s, <%s>' % (self.name, self.email)
c1 = Contacts("Grace", "something@hotmail.com")
print(c1.all_contacts)
[<__main__.Contact object at 0x0287E430>, <__main__.Contact object`
Run Code Online (Sandbox Code Playgroud)
但在这个更简单的例子中,它实际上打印:
class Example():
samplelist= [1,2,3]
test= Example()
print (test.samplelist)
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
我认为这一行是罪魁祸首:Contact.all_contacts.append(self)在第一个示例代码中.但我不确定这里发生了什么.
编辑:
一些用户告诉我只是附加self.name而不是仅仅self.
所以当我这样做时:
class Contacts:
all_contacts = []
def __init__(self, name, email):
self.name = name
self.email = email
Contacts.all_contacts.append(self.name)
Contacts.all_contacts.append(self.email)
def __str__(self):
return '%s, <%s>' …Run Code Online (Sandbox Code Playgroud)