1

Is this behaviour possible in Python?

class A():
    def __init__(self, string):
        self.string = string
    def __???__(self):
        return self.string

a = A("world")
hw = "hello "+a
print(hw)
>>> hello world

I am aware that I can do str(a), but I was wondering if it was possible to use 'a' as if it were a string-object.

2
  • 1
    One option is to subclass collections.UserString Commented Jun 26, 2017 at 19:38
  • 1
    You could implement __radd__ to control the '..' + scenario. Commented Jun 26, 2017 at 19:42

3 Answers 3

2

This works for me:

class A(str):

    def __init__(self, string):
        super().__init__()

a = A('world')
hw = 'hello ' + a
print(hw)

Output:

hello world

Testing with a custom function added:

class A(str):

     def __init__(self, string):
        self.string = string
        super().__init__()

    def custom_func(self, multiple):

        self = self.string * multiple
        return self

a = A('world')
hw = 'hello ' + a
print(hw)

new_a = a.custom_func(3)
print(new_a)

Output:

hello world
worldworldworld

Or if you do not need to do anything on initiating the class:

class A(str):
    pass

    def custom_func(self, multiple):
        self = self * multiple
        return self
Sign up to request clarification or add additional context in comments.

Comments

2

How about something like this? Using UserString from collections.

from collections import UserString

class MyString(UserString):
  pass

test = MyString('test')
print(test)
print(test + 'test')

https://repl.it/JClw/0

Comments

1

Do :

class A:
    def __init__(self, string):
        self.string = string

    # __add__: instance + noninstance
    #          instance + instance
    def __add__(self, string):
        print('__add__')
        return self.string + string

    # __radd__: noninstance + instance
    def __radd__(self, string):
        print('__radd__')
        return string + self.string


a = A("world")
hw = "hello " + a
print(1, hw)

hw = a + " hello"
print(2, hw)

hw = a + a
print(3, hw)

Output:

__radd__
(1, 'hello world')
__add__
(2, 'world hello')
__add__
__radd__
(3, 'worldworld')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.