Frank Vel
Frank Vel

Reputation: 1208

Use class object as string without using str()

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.

Upvotes: 1

Views: 282

Answers (3)

jack6e
jack6e

Reputation: 1522

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

Upvotes: 2

glegoux
glegoux

Reputation: 3623

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

Upvotes: 1

koralarts
koralarts

Reputation: 2112

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

Upvotes: 2

Related Questions