nathom791
nathom791

Reputation: 15

Why can't I concatenate these?

 class Pet:

def __init__(self, name, age):
    self.name = name
    self.age = age

def talk(self):
    raise NotImplementedError("Subclass must implement abstract method")

class Cat(Pet):

def __init__(self, name, age):
    Pet.__init__(self, name, age)

def talk(self):
    return "Meowww"

class Dog(Pet):

    def __init__(self, name, age):
        Pet.__init__(self, name, age)

    def talk(self):
        return "Woof"

def main ():

    pets = [Cat("Jess",3),Dog("Riker",2),Cat("Fred",7),Pet("thePet",5)]

    for pet in pets:
        print "Name: " + pet.name + "Age: " + str(pet.age) + ", says: " + pet.talk

    print jess.name

if __name__ == "__main__":
    main()


Traceback (most recent call last):
File "pets.py", line 36, in <module
main()
File "pets.py", line 31, in main
    print "Name: " + pet.name + "Age: " + str(pet.age) + ", says: " + pet.talk
TypeError: cannot concatenate 'str' and 'instancemethod' objects

Well, I hope that pasted correctly. I know that I need to convert the type int to str, but I don't know about why it can't concatenate with an "instancemethod." I've searched around and most other posts deal with converting int to str or whatever which are simple formatting errors. I am following this tutorial on Youtube and I've looked at it again and again and I'm pretty sure that my code is formatted correctly and matches the tutorials. Maybe I'm just missing something obvious, would really appreciate another pair of eyes on this one.

Upvotes: 1

Views: 1630

Answers (2)

user3030010
user3030010

Reputation: 1857

To add to Christian's answer, here's a brief explanation of the error you're getting:

In Python, everything is an object. In particular, functions are objects. When you see TypeError: cannot concatenate 'str' and 'instancemethod' objects, what Python is saying is that you're trying to concatenate a string and a method (function), which obviously doesn't make sense. The problem is simply that you're missing () on the end of pet.talk. It's the difference between calling a function referring to the function itself. For example, try this in a Python interpreter:

>>>def talk():
    print('Hi!')
>>>talk()
Hi!
>>>talk
<function talk at 0x00...>

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34146

You must concatenate it with the result (value returned) of that method. How do you get this result? You must call the method passing the parameters inside (...). For example:

print "Name: " + ... + pet.talk()

Upvotes: 3

Related Questions