I am new in Python OOP and I am trying to understand one line of this Code (This is just a part of the whole Code)
I am trying to understand what "pet.name" in the methode "whichone" do. The parameter 'petlist' in whichone can be empty or a list with strings. The Parameter 'name' has just one string.
Can someone explain me what "pet.name" actually do?
from random import randrange
class Pet():
boredom_decrement = 4
hunger_decrement = 6
boredom_threshold = 5
hunger_threshold = 10
sounds = ['Mrrp']
def __init__(self, name = "Kitty"):
self.name = name
self.hunger = randrange(self.hunger_threshold)
self.boredom = randrange(self.boredom_threshold)
self.sounds = self.sounds[:]
def whichone(petlist, name):
for pet in petlist:
if pet.name == name:
return pet
return None # no pet matched
def play():
animals = []
option = ""
base_prompt = """
Quit
Choice: """
feedback = ""
while True:
action = input(feedback "\n" base_prompt)
feedback = ""
words = action.split()
if len(words) > 0:
command = words[0]
else:
command = None
if command == "Quit":
print("Exiting...")
return
elif command == "Adopt" and len(words) > 1:
if whichone(animals, words[1]):
feedback = "You already have a pet with that name\n"
else:
animals.append(Pet(words[1]))
play()
CodePudding user response:
Each Pet
has a name that you give when constructing an object, that being pet.name
("Kitty" by default).
I assume whichdone()
is supposed to get a list of Pet
objects and query them against name
argument. It will return the first Pet
whose name matches a name
that you've used as input to whichdone()
.
CodePudding user response:
Assuming the petlist
parameter is a List
of Pet
objects, then the for pet in petlist
line will iterate through the list and you will be able to use the pet
variable to access the current element.
What is happening in the for loop is that you check whether the current object has the name you passed as a second parameter of the whichone
function. To do this, you'll need to access the name
attribute of the object stored in the pet
variable (which is assumed to be of type Pet
). The Python syntax for this is pet.name
(<variable_name>.<attribute_name>
).
You know of the existence of this attribute thanks to the class definition, to the __init__
method, where you can see the new instance of the Pet class will receive a name upon creation (which is defaulted to "Kitty").