Search code examples
pythonpython-3.xclasssuperclass

Calling a method returns <__main__ XYZ object at 0x01234567>


I'm going through a web-based python tutorial and the code below executes in the web environment the class has provided.

However, when I try to run the code locally in Anaconda I get the following result:

I'm Fido. I feel <bound method Pet.mood of <__main__.Pet object at 0x00000223BD4B74E0>>.

I see how using class and superclass can make my code better, and trying to figure out how to get the web based examples to work locally.

Here's the code:

class Pet:  
    def __init__(self, name = 'Kitty'):
        self.name = name
    def mood(self):
        #code simplified for SO example
        return 'happy'
    def __str__(self):
        state = "   I'm {}. I feel {}.".format(self.name, self.mood)
        return state
class Cat(Pet):
    def chasing_rats(self):
        return "I'll get you!"
p1 = Pet("Fido")
print(p1)

Solution

  • self.mood is an instance method of the class Pet. So you need to call it as a method by including the parentheses as self.mood()

    class Pet:
        def __init__(self, name = 'Kitty'):
            self.name = name
        def mood(self):
            #code simplified for SO example
            return 'happy'
        def __str__(self):
            state = "   I'm {}. I feel {}.".format(self.name, self.mood())#updated this line
            return state
    class Cat(Pet):
        def chasing_rats(self):
            return "I'll get you!"
    p1 = Pet("Fido")
    print(p1)
    

    OUTPUT

    I'm Fido. I feel happy.