Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 1
Can anyone explain me this program clearly?
class Animal: def __init__(self, name, color): self.name = name self.color = color class Cat(Animal): def purr(self): print("Purr...") class Dog(Animal): def bark(self): print("Woof!") fido = Dog("Fido", "brown") print(fido.color) fido.bark()
3 Answers
+ 3
This is OOP programming. I would recommend you to go through the python tutorial in sololearn. This will give you an explanation how your requested code is working. You should also use the "try it yourself" to practice coding.
+ 1
hi,
create one Animal class, with properties : name and color
create two subclass of Animal (Cat and Dog) with specific method : Cat -> purr() and Dog -> bark()
create a variable fido who is a Dog (so it's an Animal too and can have name -> Fido and color -> brown)
print the color of fido -> result : brown
call the fonction bark() of fido, who print "Woof" -> result "woof"
Final output result :
brown
Woof
I hope that you will understand better like this
0
There is a class Animal. The classes Cat and Dog inherit the Animal class.
When you say -
fido = Dog("Fido","brown");
// you are creating a Dog object by passing name and color. 'fido' is the reference to the object.
fido.color will return the Dog color.
fido.bark() will return the bark method which is specific to Dog class.