简体   繁体   中英

Iterating over particular attributes of instances of objects in python

I'm a novice programmer, so please pardon me for not using Python-specific vocabulary.

Suppose I define a class CarSpecs with attributes CarReg , Make , Model and Color , create several instances of this class (call them records) and one by one append them to a text file named SuperCars . What I want my program to do is to read the whole file and return the number of cars which are Red (ie by looking up the attribute Color of each instance).

Here's what I've done so far:

Defined a class:

class Carspecs(object):  
    def __init__(self, carreg, make, model, color):    
        self.CarReg = carreg   
        self.Make = make  
        self.Model = model   
        self.Color = color 

Then I created several instances and defined a function to add the instances(or you can say ''records'') to SuperCars :

def addCar(CarRecord):  
   import pickle  
       CarFile = open('Supercars', 'ab')  
       pickle.dump(CarRecord, CarFile)  
       CarFile.close()  

What do I do next to output the number of Red cars?

You'll have to open that file again, read all of the records and then see which cars Color attribute equals red. Because you're saving each instance in the pickle you will have to do something like the following:

>>> with open('Supercars', 'rb') as f:
...    data = []
...    while True:
...        try:
...            data.append(pickle.load(f))
...        except EOFError:
...            break
...
>>>
>>> print(x for x in data if x.Color == 'red')

I suggest you store the data in a list and pickle that list, this way you don't have to use that hacky loop the get all items. Storing such a list is easy. Assume you've created a list of CarSpec -objects and stored them in a list records :

>>> with open('Supercars', 'wb') as f:
...    pickle.dump(records, f)
...
>>>

and then reading it is as simple as:

>>> with open('Supercars', 'rb') as f:
...     data = pickle.load(f)
...
>>>

And you can even filter it easily:

>>> with open('Supercars', 'rb') as f:
...     data = [x for x in pickle.load(f) if x.Color == 'Red']
...
>>>

If you want to display before you're storing them in the pickle you can just iterate over the records -list and print cars with a red color.

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