0

Can anyone tell me why I didn't get the expected output?

class Pets: def __init__(self, name, type): self. name= name self. type= type def sound(self): if type =="Dog": print ("Bow Bow") else: print ("Meao") pet= Pets("Jimmy", "Dog") pet_1= Pets ("Pussy", "Cat") print (pet. name) print (pet. type) pet.sound()

21st May 2020, 9:26 PM
Sebin James
Sebin James - avatar
3 Respostas
+ 3
It should be self.type=="Dog" if that's what you want or were expecting
21st May 2020, 9:38 PM
Abhay
Abhay - avatar
+ 2
What was your expected output?
21st May 2020, 9:38 PM
HonFu
HonFu - avatar
+ 2
This code is interesting to me because it doesn't throw error as I expected: Your sound function will always print "meao". "type" here is not the "type" property of your instance but a built-in class of the language named "type". That class will never equal a string, that's why meao is printed. As Abhay said you need to use self.type because you are checking a property that belongs to your pet instance. Without "self" your code tries to find something named "type" (and succeeds) in outer scopes.
21st May 2020, 9:54 PM
Kevin ★