【问题标题】:Is there a way to force Python string concatenation op for objects?有没有办法强制对象的 Python 字符串连接操作?
【发布时间】:2017-09-13 13:42:08
【问题描述】:

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

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() 调用。可以吗?

【问题讨论】:

    标签: python string python-3.x operator-overloading


    【解决方案1】:

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

    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__,因为你的对象是左手操作符。

    但是,你真的应该使用string formatting 将对象放入字符串中:

    f"My instance is {myInstance}."
    

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

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

    【讨论】:

    • @Jean-FrançoisFabre:在这种情况下,因为它返回一个字符串,所以它可以在没有__add__ 的情况下工作。
    • 如果 concat 是 myInstance +"string",则与 __ladd__() 相同,不是吗?
    • @madtyn: 是的,在这种情况下会调用__add__(没有l)。
    • 我正在尝试这个,但最后我可能会坚持使用字符串格式的方式。
    • @madtyn:是的,这就是为什么我也给出了一个str.format() 的例子。
    【解决方案2】:

    您应该为您的代码采用format() 方法。它会自动执行此操作,并且比连接字符串更加 Pythonic。

    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))
    

    【讨论】:

      猜你喜欢
      • 2022-11-29
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多