2017-06-26 16 views
1

Ist dieses Verhalten in Python möglich?Verwenden Sie das Klassenobjekt als Zeichenfolge, ohne str() zu verwenden

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

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

Ich bin mir bewusst, dass ich tun kann, str (a), aber ich frage mich, ob es möglich war, zu verwenden ‚a‘, als wäre es ein String-Objekt.

+1

Eine Option ist 'collections.UserString' – vaultah

+1

Sie Unterklasse implementieren könnte' __radd__' zu Kontrolliere das Szenario ".." + ". –

Antwort

2

Dies funktioniert für mich:

class A(str): 

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

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

Ausgang:

hello world 

Testen mit einer benutzerdefinierten Funktion hinzugefügt:

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 

Oder wenn Sie nichts tun müssen, um auf die Einleitung der Klasse:

class A(str): 
    pass 

    def custom_func(self, multiple): 
     self = self * multiple 
     return self 
1

Sie:

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) 

Ausgang:

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

Wie wäre es so etwas? Mit UserString von collections.

from collections import UserString 

class MyString(UserString): 
    pass 

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

https://repl.it/JClw/0

Verwandte Themen