在试图弄清楚BeautifulSoup是如何工作的时候,我偶然学会了__str__
方法(我是python的新手)。因此,如果我没有误解,那么__str__
方法有助于塑造如果打印出来,将如何表示类。例如:
class Foo:
def __str__(self):
return "bar"
>>> x = Foo()
>>> print x
bar
右?所以断言我是对的,是否可以覆盖字典列表的__str__
方法?我的意思是说在Foo课你有:
class Foo:
def __init__(self):
self.l = [{"Susan": ("Boyle", 50, "alive")}, {"Albert": ("Speer", 106, "dead")}]
现在可以得到以下结果吗?
>>> x = Foo()
>>> print x.l
"Susan Boyle is 50 and alive. Albert Speer is 106 and dead."
修改
考虑到agf的解决方案,我该如何再次访问字典?我的意思是,如果我定义__str__
方法,那么显然我应该定义其他东西来检索字典。请考虑以下示例:
class PClass(dict):
def __str__(self):
# code to return the result that I want
class Foo:
def __init__(self):
self.l = PClass({"Susan": ["Boyle", ........ })
>>> x = Foo()
>>> print x.l
# result that works great
>>> y = x.l["Susan"] # this would not work. How can I achieve it?
答案 0 :(得分:22)
您需要将您正在打印的项目子类化。
from itertools import chain
class PrintableList(list): # for a list of dicts
def __str__(self):
return '. '.join(' '.join(str(x) for x in
chain.from_iterable(zip((item[0], 'is', 'and'), item[1])))
for item in (item.items()[0] for item in self)) + '.'
class PrintableDict(dict): # for a dict
def __str__(self):
return '. '.join(' '.join(str(x) for x in
chain.from_iterable(zip((item[0], 'is', 'and'), item[1])))
for item in self.iteritems()) + '.'
class Foo:
def __init__(self):
self.d = PrintableDict({"Susan": ("Boyle", 50, "alive"),
"Albert": ("Speer", 106, "dead")})
class Bar:
def __init__(self):
self.l = PrintableList([{"Susan": ("Boyle", 50, "alive")},
{"Albert": ("Speer", 106, "dead")}])
foo = Foo()
print self.d
bar = Bar()
print self.l
答案 1 :(得分:4)
另一种方法是覆盖__getattribute__
,它允许您自定义返回属性的方式:
class Foo(object):
def __init__(self):
self.l = [{"Susan": ("Boyle", 50, "alive")}, {"Albert": ("Speer", 106, "dead")}]
def __getattribute__(self, name):
return PrintableList(l)
attr = super(Foo, self).__getattribute__(name)
items = sum([x.items() for x in attr], [])
return ' '.join([' '.join([k, v[0], 'is', str(v[1]), 'and', v[2] + '.']) for k,v in items])
>>> f = Foo()
>>> print f.l
<<< Susan Boyle is 50 and alive. Albert Speer is 106 and dead.
答案 2 :(得分:0)
您可以为您的Foo类定义__str__
以返回您想要的内容:
class Foo():
def __init__(self):
self.l = [{"Susan": ("Boyle", 50, "alive")}, {"Albert": ("Speer", 106, "
dead")}]
def __str__(self):
ret_str = ""
for d in self.l:
for k in d:
ret_str += "".join([k, " ", d[k][0], " is ", str(d[k][1]), " and
", d[k][2], ". "])
return ret_str
foo = Foo()
print foo
结果:
Susan Boyle现年50岁。阿尔伯特施佩尔已经106岁了。