Skip to main content
 首页 » 编程设计

python之为什么我不能在一个类中连接 'str' 和 'instance' 对象

2025年05月04日25langtianya

class myClass: 
 
    def __init__(self, text): 
            self.text = text 
 
    def printText(text): 
            more_text = "Why so " 
 
            return more_text + text 

以上是我正在构建的用于从网页中提取数据的代码的过度简化版本。我正在像这样运行 temp.py 代码。

>>> from temp import myClass 
>>> text = "serious?" 
>>> joker_says = myClass(text) 
>>> 
>>> print joker_says.printText() 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "temp.py", line 9, in printText 
    return more_text + text 
TypeError: cannot concatenate 'str' and 'instance' objects 

我在 Stack Overflow 中看到了很多关于“str”和“instance”对象的串联问题的例子。

我试过以下方法:

选项 1:在 init 作为输入期间将文本转换为字符串

class myClass: 
 
    def __init__(self, str(text)): 
            self.text = text 
 
    def printText(text): 
            more_text = "Why so " 
 
            return more_text + text 

但是我得到...

Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "temp.py", line 3 
    def __init__(self, str(text)): 
                      ^ 
SyntaxError: invalid syntax 

== == == == == ==

选项 2:在 init 步骤中将文本转换为字符串

class myClass: 
 
    def __init__(self, text): 
            self.text = str(text) 
 
    def printText(text): 
            more_text = "Why so " 
 
            return more_text + text 

但是我得到...

Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "temp.py", line 9, in printText 
    return more_text + text 
TypeError: cannot concatenate 'str' and 'instance' objects 

有人可以给我一个好的解决方案吗?请注意,在我的原始代码中,我的意图是在类中连接两个字符串对象以创建网页链接。任何建议将不胜感激。

请您参考如下方法:

这里有几个问题:

在为对象创建的每个函数中,self 都必须作为第一个参数。

使用你的第二个例子:

class myClass: 
 
    def __init__(self, text): 
            self.text = str(text) 
 
    def printText(self, text): 
            more_text = "Why so " 
 
            return more_text + text 

然后,创建类的一个实例,然后就可以访问函数 printText :

joker = myClass("This is some text") 
print(joker.text) # This prints: "This is some text" 
print(joker.printText("serious?")) # This prints "Why so serious?" 

如果你想使用与初始化文本相同的文本,你需要引用它,而不是作为新参数 text,作为类的属性,如下所示:

class myClass: 
 
    def __init__(self, text): 
            self.text = str(text) 
 
    def printText(self): 
            more_text = "Why so " 
 
            return more_text + self.text 

然后,如果你想引用上面的内容:

joker = myClass("serious?") 
print(joker.text) # This prints: "serious?" 
print(joker.printText()) # This prints "Why so serious?"