python - `format()` 和 `str()` 之间有什么区别?

标签 python python-3.x io

>>> format(sys.stdout)
"<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>"
>>> str(sys.stdout)
"<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>"

我不太确定以下来自 Python 库引用的引用。 format() 之间有什么区别和str() ,或object.__format__(self, format_spec)之间和object.__str__(self ) ?我们什么时候使用哪个?

object.__str__(self )

Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object.

object.__format__(self, format_spec)

Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method, to produce a “formatted” string representation of an object.

最佳答案

我将分解主要的三个(技术上主要是 2,因为 __format__ 并未普遍实现)。我将完成所有三个类(class),然后将它们放在一个很好的类(class)中。

<小时/>

最常见的__str__:

这就是您想要将此对象表示为 str 的方式。 通常,这没有 __repr__ 详细,并且被使用 主要针对最终用户。例如,如果我们有一个 person 类,我们可以这样实现 str:

class Person:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return f"Hello my name is {self.name}" 

p = Person("John Smith")
print(str(p)) # Prints "Hello my name is John Smith"
<小时/>

不太常见的__repr__:

说实话,对于大多数项目来说,我实现这个的次数比 str 还要多。这应该以 str 的形式返回对象的表示形式,以便对开发人员而不是最终用户有帮助,并通过 repr( my_obj)。如果一个类没有实现 __str__ 魔术方法,那么当你使用 str(my_obj) 时,Python 将尝试自动调用它的 __repr__ 方法(因此您可以先实现 repr,然后再实现 str)。通常,类的 repr 返回重新创建该对象的方法。例如:

class Person:
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return f"Person(name='{self.name}')"

p = Person("John Smith")
print(repr(p)) # Prints "Person(name='John Smith')"
print(str(p))  # Prints "Person(name='John Smith')"
<小时/>

被诅咒的 child __format__:[我只是这样调用它,因为它很少使用:)]

__format__ 与其他两种方法的主要区别在于,它还接受可用于设置返回字符串样式的 format_spec

为了更详细地理解这一点,我必须首先解释一些格式化的东西。您以前可能见过其中一些内容,也可能没有见过。

让我们使用一个虚拟类:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __repr__(self):
        return f'Person(name="{self.name}", age={self.age})'
    def __str__(self):
        return str(self.name)

p = Person(name="John Smith", age=22)
# This prints the str of p
print("{!s}".format(p)) # John Smith
# This prints the representation of p
print("{!r}".format(p)) # Person(name="John Smith", age=22)

好吧,您可以将类格式化为其 strrepr,但是如果您想以自己的方式格式化它怎么办?大多数人不需要这样做;但是,这就是Python的力量,你可以做任何事情。我们可以创建不同的标签来代替 rs (尽管它使用 : 而不是 !):

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __repr__(self):
        return f'Person(name="{self.name}", age={self.age})'
    def __str__(self):
        return str(self.name)
    def __format__(self, format_spec):
        if format_spec == 'age': # get a persons age
            return f"{self.name} is {self.age} years old"
        elif format_spec == 'birthday':
            return "Yesterday"
        return str(self) # A default case

p = Person(name="John Smith", age=22)
# This prints the str of p
print("{!s}".format(p))
# This with representation of p
print("{!r}".format(p))
print("{:age}".format(p))
print("{:birthday}".format(p))
print(f"{p:age} and his birthday was {p:birthday}")

这显然超出了我有限的知识所能涉及的范围,但这应该是一个很好的一般范围:)。

有一些包使用它,例如datetime。如果您有兴趣进一步了解格式的强大功能,Pyformat 可以很好地介绍这一点:PyFormat .

免责声明:

我没有太多使用__format__的经验,所以我无法提供一个好的用例(尽管datetime的用例还不错)。这里的所有内容只是为了展示 strreprformat 魔术方法之间的广泛差异。如果我有任何错误(尤其是 __format__ 的用例),请告诉我,我会更新它。

关于python - `format()` 和 `str()` 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56403584/

相关文章:

Python 不能根据两个整数的值给字符串赋值

python - Crontab 没有名为 Pandas 的模块

python - 如何编写一个接受包含整数元素的元组的函数?

python - 如何用图像中每个像素的颜色绘制图形?

java - 关闭时未删除临时文件

java - 如何读取附加到我已读取的文件末尾的文本?

python - 两行 Python 代码导致 3 个执行 block

python - 使用 codecs.open() 访问内存中的解压文件

python - 对字典中的值进行排序 Python 3 - Highscores

python - 初学者 Python : Reading and writing to the same file