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)