如果我尝试打印作为列表的类变量,我会得到一个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>' % (self.name, self.email)
def __repr__(self):
return str(self)
c1 = Contacts("Paul", "something@hotmail.com")
c2 = Contacts("Darren", "another_thing@hotmail.com")
c3 = Contacts("Jennie", "different@hotmail.com")
print(Contacts.all_contacts)
Run Code Online (Sandbox Code Playgroud)
我明白了:
['Paul', 'something@hotmail.com', 'Darren', 'another_thing@hotmail.com', 'Jennie', 'different@hotmail.com']
Run Code Online (Sandbox Code Playgroud)
代替:
[Paul, <something@hotmail.com>, Darren, <another_thing@hotmail.com>, Jennie, <different@hotmail.com>]
Run Code Online (Sandbox Code Playgroud)
因此,__str__方法中的格式不起作用.
Ana*_*mar 13
当您打印列表时,它会调用__str__列表,但列表会在内部调用__repr__()其元素.您也应该__repr__()为您的班级实施.示例 -
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)
def __repr__(self):
return str(self)
Run Code Online (Sandbox Code Playgroud)
演示 -
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)
def __repr__(self):
return str(self)
contact1 = Contacts("Grace1", "something1@hotmail.com")
contact2 = Contacts("Grace2", "something2@hotmail.com")
contact3 = Contacts("Grace3", "something3@hotmail.com")
print(Contacts.all_contacts)
Run Code Online (Sandbox Code Playgroud)
结果 -
[Grace1, <something1@hotmail.com>, Grace2, <something2@hotmail.com>, Grace3, <something3@hotmail.com>]
Run Code Online (Sandbox Code Playgroud)
此外,从输出看起来列表实际上有6元素,所以你应该考虑改变__repr__返回.
| 归档时间: |
|
| 查看次数: |
163 次 |
| 最近记录: |