Let's say we have a Pet class in Python:
class Pet(object):
num_pets = 0
def __init__(self, name):
self.name = name
Pet.num_pets += 1
def speak(self):
print("My name's %s and the number of pets is %d" % (self.name, self.num_pets))
I want the init method to create an instance, but also update an attribute on the class. Is there a more elegant way to do this than the code above? I tried passing in self
and cls
to the init method, and then referring to cls instead of Pet where num_pets is incremented, but that didn't work.
num_pets
is an attribute that's managed per-class. I don't see any obvious reason why to consider the need of using a class method here. – Knecht