简体   繁体   中英

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

Above is a over-simplified version of a code that I am constructing to extract data out of webpages. I am running the temp.py code like this.

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

I have seen many examples of concatenation issues of 'str' and 'instance' objects in Stack Overflow.

I have tried the following ways:

OPTION 1: CONVERT text TO STRING DURING init AS INPUT

class myClass:

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

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

            return more_text + text

But I get ...

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

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

OPTION 2: CONVERT text TO STRING DURING init STEP

class myClass:

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

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

            return more_text + text

But I get...

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

Can someone please give me a good solution to the problem? Please note that in my original code, my intention is to concatenate two string objects inside the class to create a webpage link. Any suggestion would be appreciated.

You have a couple issues here:

On every function you create for an object, self must be included as the first parameter.

Using your second example:

class myClass:

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

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

            return more_text + text

Then, you make an instance of your class, and you can access the function 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?"

If you want to use that same text as the initializing text, you need to reference it, instead of as a new parameter text , as an attribute of the class, as so:

class myClass:

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

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

            return more_text + self.text

Then, if you want to reference the above:

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

The main problem you are facing is this:

def printText(text):

The reason why you are getting this error is because, as an instance method, the declaration expects you to have self (the instance object) passed as first argument. You are now passing text which is being used as self (the instance). This is why you get the error, because ultimately what you are actually doing is trying to add a string with an instance.

So, knowing that the first argument being passed implicitly to printText is the instance, and looking inside your method, you are actually wanting to reference the self.text inside your printText method. However, your instance being passed in to printText is actually referred to as text . This can be very confusing.

So, following the suggested nomenclature, you should be naming your instance argument as the "expected", self.

With this in mind, your text that you want to reference, can now be referenced as self.text .

This can be shown by fixing your code:

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

        return more_text + self.text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM