gpt4 book ai didi

python __str__ 用于对象

转载 作者:IT老高 更新时间:2023-10-28 20:34:02 24 4
gpt4 key购买 nike

在试图弄清楚 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?

最佳答案

您需要对要打印的项目进行子类化。

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

关于python __str__ 用于对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7152312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com