Question

Could I please get some help. I've been trying out OOP on python 3.3. I have however encountered problems with printing my output. Here is an example:

class pet(object):
    number_of_legs = 0
    def sleep (self):
        print('Zzzzz')
    def count_legs(self):
        print ('I have %s legs' %(self.number_of_legs))

nemo = pet ()
nemo.number_of_legs = 4
nemo.count_legs
nemo.sleep

output:

bound method pet.count_legs of <__main__.pet object at 0x033D4230>
bound method pet.sleep of <__main__.pet object at 0x033D4230>

Any tips on overcoming this issue would be of a great help.

Thanks.

Was it helpful?

Solution

You need to actually call the methods, using (), even if there are no arguments:

nemo.count_legs()
nemo.sleep()

A method is really just a callable attribute; you get the method object itself with instance.attribute, and call it using parentheses instance.attribute().

Also, note that number_of_legs, as you currently have it, is a class attribute, shared by all instances. Assuming that different pets can have different numbers of legs, I would instead make it an instance attribute, which you can do at initialisation:

class Pet:

     def __init__(self, legs):
         self.legs = legs

     def sleep(self):
         print("Zzz")

     def count_legs(self):
         print("I have {0.legs} legs.".format(self))

(classes are named with uppercase by convention/PEP-008 and str.format, unlike %, isn't deprecated). You can now make e.g.

nemo = Pet(4)

OTHER TIPS

You have to include the ():

nemo = pet ()
nemo.number_of_legs = 4
nemo.count_legs()
nemo.sleep()

That way, you are actually making the method call instead of getting the method.

[OUTPUT]
I have 4 legs
Zzzzz
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top