I have a parent class Animal and child class Dog. I wanted to create 1 instance of each and print the their count. Here is the working code:
class Animal:
count=0
def __init__(self):
Animal.count+=1
@classmethod
def getCount(cls):
return cls.count
class Dog (Animal):
count=0
def __init__(self):
super().__init__()
Dog.count+=1
a1=Animal()
print(Animal.getCount(),Dog.getCount())
d1=Dog()
print(Animal.getCount(),Dog.getCount())
It prints:
1 0
2 1
which is correct as there are 2 animals but only 1 of them is dog.
The problem occurs when i create count variable as private __count without changing any other piece of code.
class Animal:
__count=0
def __init__(self):
Animal.__count+=1
@classmethod
def getCount(cls):
return cls.__count
class Dog (Animal):
__count=0
def __init__(self):
super().__init__()
Dog.__count+=1
a1=Animal()
print(Animal.getCount(),Dog.getCount())
d1=Dog()
print(Animal.getCount(),Dog.getCount())
Now, it prints:
1 1
2 2
Seems like Dog class is only accessing the Animal's __count.
Can you detect the bug in the code?