【发布时间】:2017-07-22 02:51:07
【问题描述】:
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
有人可以给我一个很好的解决问题的方法吗?请注意,在我的原始代码中,我的意图是在类中连接两个字符串对象以创建网页链接。任何建议将不胜感激。
【问题讨论】:
-
因为
printText中的text是您的方法 的第一个参数,所以它*隐式传递给了实例,因此它不起作用。
标签: python string class instance init