Python类的\uu str \uuu()能否返回两个字符串中的一个?

2024-03-29 07:11:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类,我希望能够打印一个对象的短字符串表示或长字符串表示。理想情况下,__str__()会接受一个选择返回哪个字符串的标志,print()也会接受这个标志,并相应地使用__str__()的正确版本,但似乎不存在类似的情况。你知道吗

我知道我可以在我的类中包含print_short()print_long()方法来选择正确的字符串,但是这看起来不像Python,并且违反了python3的更改,其中print()是一个函数。这也会绕过__str__()的使用,这似乎也是不和谐的。你知道吗

处理这件事的最邪恶的方法是什么?涉及__repr__()的解决方案将不起作用,因为我已经按照预期使用了__repr__(),以明确地表示对象本身。你知道吗


Tags: 对象方法函数字符串版本标志情况解决方案
1条回答
网友
1楼 · 发布于 2024-03-29 07:11:38

str的工作是提供对象的“字符串”表示,您决定的任何表示都是最有用的。你知道吗

如果要控制对象的格式化,请重写__format__。你知道吗

class MyClass:

    def __format__(self, spec):
        ...

如果你有这样的代码

s = MyClass()
print("{:r}".format(s))

s.__format__接收冒号后面的所有内容(在本例中是r)作为其spec参数;然后完全取决于__format__的定义它如何使用spec来决定返回哪个字符串值。你可以这样做

class MyClass:
    def __format__(self, spec):
        if spec == 's':
            return self._short_str()
        elif spec == 'l':
            return self._long_str()
        else:
            # This includes both no spec whatsoever, which is
            # conventionally expected to behave like __str__
            # and an unrecognized specification, which is just ignored.
            return str(self)

    def _long_str(self):
        return "three"

    def _short_str(self):
        return "3"

    def __str__(self):
        return "III"

>>> x = MyClass()
>>> str(x)
'III'
>>> "{}".format(x)
'III'
>>> "{:whatever}".format(x)
'III'
>>> "{:s}".format(x)
'3'
>>> "{:l}".format(x)
'three'

相关问题 更多 >