简体   繁体   中英

Creating instances efficiently in Python

So I have a program in which I need to create 4 instances of a class with variables imported from an external document. I have a solution and I have placed it below, but I want to know if there's an easier/more efficient way to do it, perhaps with a for loop.

partsLine = partsDoc.readline()
partsList = partsLine.split(' ')
part1 = Parts(partsList[0], partsList[1], partsList[2],)

partsLine = partsDoc.readline()
partsList = partsLine.split(' ')
part2 = Parts(partsList[0], partsList[1], partsList[2],)

partsLine = partsDoc.readline()
partsList = partsLine.split(' ')
part3 = Parts(partsList[0], partsList[1], partsList[2],)

partsLine = partsDoc.readline()
partsList = partsLine.split(' ')
part4 = Parts(partsList[0], partsList[1], partsList[2],)

Rule of thumb: if you have multiple variables with the same name except for a number at the end, replace all of them with a list.

my_parts = []
for i in range(4):
    partsLine = partsDoc.readline()
    partsList = partsLine.split(' ')
    my_parts.append(Parts(partsList[0], partsList[1], partsList[2],))

You can still refer to individual parts using indexing, eg my_parts[2] , so you haven't lost any expressiveness by doing so.

Produce a list of the parts, don't use individual partN variable names. Limit reading lines from the file to the first four with itertools.islice() :

from itertools import islice

parts = []
for line in islice(partsDoc, 4):
    part = Parts(*line.split(None, 3)[:3])  # apply the first 3 elements as arguments
    parts.append(part)

This can be further reduced using a list comprehension:

parts = [Parts(*line.split(None, 3)[:3]) for line in islice(partsDoc, 4)]

From here on out you can address these four parts with indexing:

parts[2]

gives you the results of the 3rd line in the file.

Note that I replaced str.split(' ') with str.split(None, 3) ; this changes the split behaviour to strip off extra whitespace at the start and end, and to limit the number of splits made to just what you need and no more.

Basic Version

Using a function to create a new Parts instance:

def make_part(parts_doc):
    parts_line = parts_doc.readline()
    parts_list = parts_line.split(' ')
    return Parts(parts_list[0], parts_list[1], parts_list[2])

you can use it in a list comprehension:

parts = [make_part(parts_doc) for _ in range(4)]

Retrieve the instances through indexing:

parts[0]

Incremental Improvement I - Make the function take a line

def make_part_from_line(parts_line):
    parts_list = parts_line.split(' ')
    return Parts(parts_list[0], parts_list[1], parts_list[2])

A file object is an iterator that returns the next line using next :

parts = [make_part_from_line(next(parts_doc)) for _ in range(4)]

Incremental Improvement II - Shorten the function

def make_part_from_line(parts_line):
    return Parts(*parts_line.split(' ')[:3])

The * -syntax unpacks the list into three function arguments.

Incremental Improvement III - Make it a one-liner

The function has only one line. Use it directly:

parts = [Parts(*next(parts_doc).split(' ')[:3]) for _ in range(4)]

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