New course! Every coder should learn Generative AI!
Try a free lesson+ 2
What is the output of this code?
What is the output of this code? class Animal: i = 0 def _init._(self, name): self.name = name Animal.i += 1 class Cat(Animal): i = Animal.i def _init_(self, name): self.name = name Cat.i += 1 sylvester = Cat('Sylvester') print(Cat.i)
2 Answers
+ 2
1.
To understand what this code is doing, the Cat class has a class attribute called i. Everytime an object of type 'Cat' is initialized, i is incremented by 1.
So here you create one Cat object and print the value of i. I think you know what's going to happen.
HonFu looking at how this is a quiz question, I think he is wanting an explanation rather that posing a challenge to the community.
+ 2
Please just run it in Code Playground and see for yourself.
Or ask us specifically what you don't understand.