有没有办法强制Python字符串连接op对象?

时间:2017-09-13 13:42:08

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

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

__str__()

这将转到MyClass中的message = "My instance is " + myInstance + "." 方法并成功打印该行,就像我从查看python文档时所记得的那样。

但是,为了实现这个目的,一些运算符重载是不可能的?:

str()

我只是好奇,因为我认为这可能是可能的,但我无法在python文档中找到它。在这种情况下我有一个对象,并认为我可以做得更短,并且还在类层次结构的根中实现运算符重载,从而节省了孩子们的写作。

我想我无法解决func getTabImage(url: URL) -> UIImage { Alamofire.request(url) .responseImage { response in if let image = response.result.value { return image } else { print("Failed to get image") } } } 电话问题。我可以吗?

2 个答案:

答案 0 :(得分:4)

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

#define NAME_OUT(name_in)  PRE_##name_in##_POST

演示:

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

当您的对象是左手操作符时,您可能也希望实现__add__

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

>>> 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.'

f"My instance is {myInstance}."

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

答案 1 :(得分:0)

您应该为代码采用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))