有没有办法强制对对象进行Python字符串连接操作?

mad*_*tyn 0 python string operator-overloading python-3.x

我对拥有一个类和该类的实例并将它们连接起来有一些疑问。通常是:

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)
Run Code Online (Sandbox Code Playgroud)

正如我在查看 python 文档时记得的那样,这将转到__str__()in 的方法并成功打印该行。MyClass

但是,不可能通过某些运算符重载来实现这一点吗?:

message = "My instance is " + myInstance + "."
Run Code Online (Sandbox Code Playgroud)

我只是很好奇,因为我认为这是可能的,但我在 python 文档中找不到这个。在这种情况下,我有一个对象,并且认为我可以做得更短,并且还在类层次结构的根中实现运算符重载,从而保存子级中的写入。

我想我无法解决这个str()问题。我可以吗?

Mar*_*ers 5

您可以实现__radd__钩子来捕获添加到另一个对象的情况:

def __radd__(self, other):
    return other + str(self)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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.'
Run Code Online (Sandbox Code Playgroud)

你可能想要实现__add__当您的对象是左侧运算符时,

但是,您确实应该使用字符串格式将对象放入字符串中:

f"My instance is {myInstance}."
Run Code Online (Sandbox Code Playgroud)

或者

"My instance is {}.".format(myInstance)
Run Code Online (Sandbox Code Playgroud)

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

  • @madtyn:是的,在这种情况下会调用`__add__`(没有`l`)。 (2认同)