简体   繁体   中英

Python: How do I search through an array of objects

How do I search through an array of objects, and return and print all of its relevant properties based on the ID that the user has input. PS: You can just ignore most of the code and just scroll to the last part of the code which is relevant.

TheArray is the array which the objects are being stored into

Example Code:

class User():
    def __init__(self,Number,Name):
        ID = Number
        User = Name
    def Get_ID(self):
        return Number
class Telephone(User):
    def __init__(self,Number,Name,TelephoneNumber):
        User.__init__(self,Number,Name)
        Telephone = TelephoneNumber
    def Get_Telephone(self):
        return Telephone

TheArray = []
Phone = Telephone(1, "Marc", 8888)
TheArray.append(Telephone)
Phone = Telephone(1, "Jack", 9999)
TheArray.append(Telephone)

You can use __dict__ to get object's property. Like below:

counter = 0
TheArray = []
while Counter < 18:
    VehicleClass = Vehicle("Red Sports Car", "RSC13", 15.00, Counter, "Car", 3.3, 12.1, 0.08)
    TheArray.append(VehicleClass)
    Counter = Counter + 1
print(TheArray)

for obj in TheArray:
    print(obj.__dict__)

Hope it would help you..!!

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