How to combine an "object" with a string?

How to bind Object to a string (primitive) without overloading and cast ( str() ) explicit type?

 class Foo: def __init__(self, text): self.text = text def __str__(self): return self.text _string = Foo('text') + 'string' 

Conclusion:

 Traceback (most recent call last): File "test.py", line 10, in <module> _string = Foo('text') + 'string' TypeError: unsupported operand type(s) for +: 'type' and 'str' 
Operator

+ should be overloaded? Are there any other ways (just interesting)?

PS: I know about operator overloads and casting types (e.g. str(Foo('text')) )

+6
source share
3 answers

Just define the __add__() and __radd__() methods:

 class Foo: def __init__(self, text): self.text = text def __str__(self): return self.text def __add__(self, other): return str(self) + other def __radd__(self, other): return other + str(self) 

They will be called depending on whether you execute Foo("b") + "a" (calls __add__() ) or "a" + Foo("b") (calls __radd__() ).

+10
source
 _string = Foo('text') + 'string' 

The problem with this string is that Python thinks you want to add string to an object of type Foo , and not vice versa.

This would work if you wrote:

 _string = "%s%s" % (Foo('text'), 'string') 

EDIT

You can try it with

 _string = 'string' + Foo('text') 

In this case, your Foo object should be automatically added to the string.

+4
source

If this makes sense for your Foo object, you can overload the __add__ method as follows:

 class Foo: def __init__(self, text): self.text = text def __str__(self): return self.text def __add__(self, other): return str(self) + other _string = Foo('text') + 'string' print _string 

Output Example:

 textstring 
+1
source

Source: https://habr.com/ru/post/908636/


All Articles