简体   繁体   中英

How do I display an entire object that matches my search by an attribute of that object in Python?

I am writing a program that keeps track of the animals on a farm and I want to be able to search for an animal by eg: name, gender, age etc, which all are attributes to the objects. I am a complete noob when it comes to Python so all help is very appreciated.

Here is the code i have so far for this, but it only ads the attribute that is searched for to the list and then prints it. I want to be able to add the entire object to the list and print the whole object through that list.

class Djur:

    def __init__(self, art, namn, ålder, kön, gravid):
        self.art = art
        self.namn = namn
        self.age = ålder
        self.gender = kön
        self.gravid = gravid


    def __str__(self):
        return ("Art: " + str(self.art) + " " + "\n"
                "Namn: " + str(self.namn) + " " + "\n"
                "Ålder: " + str(self.age) + " " + "\n"
                "Kön: " + str(self.gender) + " " + "\n"
                "Gravid: " + str(self.gravid))
    def __repr__(self):
        return str(self)




try:

                val2 = input("Ange sök-text")

                l=[]

                for x in djurlista:
                    y = x.art or x.gender or x.namn or x.gravid or x.age
                    if y == val2:
                        l.append(x.art)
                        print(l)
                meny()


            except ValueError:
                print("Var god välj ett giltigt alternativ!")

To create a list with the objects you just need to write l.append(x) instead of l.append(x.art) . Now you are just appending the property art .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM