是否有一种方法可以强制对象的Python字符串串联OP



我对参加该类别的课程和实例和串联有一些疑问。通常是:

class MyClass(object):
    # __init__, more code and so on...
    def __str__(self):
        return "a wonderful instance from a wonderful class"
myInstance = MyClass()
message = "My instance is " + str(myInstance) + "."
print(message)

这将转到MyClass中的__str__()方法并成功打印了行,就像我从查看Python文档中所记得的那样。

但是,不可能有些操作员超负荷以使其成为可能?:

message = "My instance is " + myInstance + "."

我只是好奇,因为我认为这是可能的,但我在Python文档中找不到这一点。在这种情况下,我有一个对象,并认为我可以做更短的时间,并且还以级别的层次结构的根源实现了操作员的重载。

我想我无法解决str()调用。我可以吗?

您可以实现__radd__钩以捕获被添加到另一个对象:

def __radd__(self, other):
    return other + str(self)

演示:

>>> class MyClass(object):
...     # __init__, more code and so on...
...     def __str__(self):
...         return "a wonderful instance from a wonderful class"
...     def __radd__(self, other):
...         return other + str(self)
...
>>> "My instance is " + MyClass() + "."
'My instance is a wonderful instance from a wonderful class.'

您可能也想实现__add__,因为当您的对象是左手操作员时。

但是,您应该真正使用字符串格式将对象放入字符串:

f"My instance is {myInstance}."

"My instance is {}.".format(myInstance)

这调用对象上的 __format__()钩子,默认情况下,将对象转换为字符串。

您应采用代码的format()方法。它会自动做到这一点,并且比串联串联更重要。

class MyClass(object):
    # __init__, more code and so on...
    def __str__(self):
        return "a wonderful instance from a wonderful class"
my_instance = MyClass()
print("My instance is {}.".format(my_instance))

最新更新