2017-06-26 39 views
1

這種行爲在Python中可行嗎?使用類對象作爲字符串而不使用str()

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

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

我知道我可以做STR(一),但我想知道是否有可能使用「一」就好像它是一個字符串對象。

+1

一種選擇是繼承'collections.UserString' – vaultah

+1

您可以實現'__radd__'到控制'''+'場景。 –

回答

2

這個工作對我來說:

class A(str): 

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

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

輸出:

hello world 

測試使用自定義功能補充說:

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) 

輸出:

hello world 
worldworldworld 

或者,如果你不需要在啓動類做任何事情:

class A(str): 
    pass 

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

做:

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) 

輸出:

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

怎麼這樣呢?使用來自collectionsUserString

from collections import UserString 

class MyString(UserString): 
    pass 

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

https://repl.it/JClw/0

相關問題