1

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()
3
  • 3
    The parameter petlist must be a list of Pet Commented Jul 4, 2022 at 13:59
  • What's your python version? Commented Jul 4, 2022 at 14:01
  • 2
    The parameter 'petlist' in whichone can be empty or a list with strings. are you are about that latter? If not try to call whichone with 1st argument being list of strs and observe what would happen. Commented Jul 4, 2022 at 14:07

2 Answers 2

2

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").

Sign up to request clarification or add additional context in comments.

6 Comments

I wasn't aware that petlist is a List of Pet objects. I thought it is a List of str. How can I see that it is a List of Pet objects? I mean in the function play(), you can see "animals = []". So for me it seems just a empty list.
You can partly verify it where the function is used. Here the only occurrence of this function is whichone(animals, words[1]) with animals being declared as a List (animals = []) and having only Pet instances added into it (the only occurrence of elements being put in animals is animals.append(Pet(words[1])).
You can also reason the other way around and ask yourself "What can it be?" and look at the whichone function. By analyzing it, you can deduce that the petlist argument needs to be a List (because of the use of a for loop). Also, the elements that are in the List must have a name attribute (because the pet.name syntax means that you are accessing the name attribute of the variable, which here is an element of the list. As you will go through all the elements in the list, they all must have this attribute). In theory, this could be a list of anything that has a name attribute
Additionally, you generally try and be coherent with your variable names when writing a program. In this case, petlist is pretty self-explanatory. (Don't take the name as a proof of what this is, errors are made, but this can generally be a strong indicator)
Yes, it has been answered.
|
2

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.