为什么我不能在 class 中连接 'str' 和 'instance' 对象?

Why can I not concatenate 'str' and 'instance' objects inside a class?

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

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

您面临的主要问题是:

def printText(text):

您收到此错误的原因是,作为实例方法,声明期望您将 self(实例对象)作为第一个参数传递。您现在传递的 text 被用作 self (实例)。这就是你得到错误的原因,因为最终你实际做的 试图添加一个带有实例的字符串。

因此,知道隐式传递给 printText 的第一个参数是实例,并且查看您的方法内部,您 实际上 想要引用 self.text 在你的 printText 方法中。但是,传递给 printText 实例 实际上被称为 text。这可能非常令人困惑。

因此,按照建议的命名法,您应该将实例参数命名为 "expected",self。

考虑到这一点,您要引用的 text 现在可以引用为 self.text

这可以通过修复您的代码来证明:

def printText(self):
        more_text = "Why so "

        return more_text + self.text

你有几个问题:

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

使用你的第二个例子:

class myClass:

    def __init__(self, text):
            self.text = str(text)

    def printText(self, text):
            more_text = "Why so "

            return more_text + text

然后,创建 class 的实例,您可以访问函数 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 的属性,如下所示:

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?"