class Cat:
MEOWS = 3
def meow(self):
for _ in range(Cat.MEOWS):
print("meow")
cat = Cat()
cat.meow()
2 Answers
the __init__()
method is primarily used to create class objects with different attribute values. Since you are hard coding the attribute MEOWS=3
for every class instance, you don't need it.
Suppose you want to define the number of meows a cat makes. Then you need to create the MEOWS attribute in __init__()
(and modify the meow()
method to use the self.MEOWS
value). See below for an example:
class Cat():
def __init__(self, n_meows):
self.MEOWS = n_meows
def meow(self):
for _ in range(self.MEOWS):
print("meow")
print('*****')
cat3 = Cat(3)
cat3.meow()
cat5 = Cat(5)
cat5.meow()
The MEOWS attribute is a class-level attribute and is shared among all instances of the class. The meow method also does not require any instance-level data, as it only operates on the class-level MEOWS attribute. Thus, the init function is not necessary in this case.