Skip to main content
 首页 » 编程设计

python之在不使用 str() 的情况下将类对象用作字符串

2025年05月04日37lovecherry

这种行为在 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 

我知道我可以执行 str(a),但我想知道是否可以将 'a' 用作字符串对象。

请您参考如下方法:

这对我有用:

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)时不需要做任何事情:

class A(str): 
    pass 
 
    def custom_func(self, multiple): 
        self = self * multiple 
        return self