I am really new to Python, and I'm having difficulty with classes. I created a class Pet with name and type attributes.
class Pet:
def __init__(self, name, type):
self.name = name
self.type = type
def getName(self):
return self.name
def getType(self):
return self.type
def setName(self, name):
self.name = name
def setType(self, type):
self.type = type
def print(self):
print("{} is a {}".format(self.name, self.type))
I created instances? of this class and appending them to a list.
listPets = []
pet1 = Pet("Hobo", "dog")
pet2 = Pet("Pal", "dog")
pet3 = Pet("Meow", "cat")
listPets.append(pet1)
listPets.append(pet2)
listPets.append(pet3)
My main goal is to print the name of the pets that are dogs.
for p in listPets:
if Pet.getType() == "dog":
print(p.getName())
I get a TypeError with getType() missing 1 positional argument: 'self'.
CodePudding user response:
You should be calling p.getType()
p
is the instance of the class, not Pet
CodePudding user response:
When you are using p
variable for items in listPets
then you should use p
in the conditional statement too.
Replace, if Pet.getType() == "dog":
with if p.getType() == "dog":
Since Pet
is not an instance of class, when you call any method of class for Pet
it gives error.
CodePudding user response:
Class is like a special type. When you create a class, you are essentially creating a type that have some specific functions attached to it. Now, you can make variables of this type (object) and do stuff with it. So, when you want to do something with your variable (object here) you use your variable not the typename (e.g. int int
). To make it a bit more clear, list
is a class. Say, you declare a list l = [1,2]
and now append 3 to this list. You would write l.append(3)
not list.append(3)
. That was the error in your code, Pet.getType()
. Your variable is p
, so, you have to call by p
as p.getType()
.