简体   繁体   中英

Trying to pass parameters as functions in Python

I have this:

class Student:
    def __init__(self, FirstName, LastName):
        self.FirstName = FirstName
        self.LastName = LastName

    def __iter__(self):                                            
        return self

Students = [
#       FirstName   LastName   
Student("Mary",     "Smith"),
Student("Joe",      "Jones"),    
Student("Jane",     "Doe"  )]

I make a Student class. And then I make a list of 3 Student objects. Then I can print a list of the names like this:

for item in Students:
    print item.FirstName, item.LastName

And it obediently outputs this:

Mary Smith
Joe Jones
Jane Doe

Then I googled how to sort a list of objects by an attribute and found this:

Students.sort(key = lambda x: x.LastName)

And it works. That line sort the list by the LastName attribute and I can print it the same way as above and the names are in order by LastName :

Jane Doe
Joe Jones
Mary Smith

But what I want to happen is have user inputs for what list to sort ( sortlist ) and by which attribute to sort by ( sortby ). So I tried:

def sort(sortlist, sortby):
    sortlist.sort(key = lambda x: x.sortby)

sort(Students, FirstName) 

And that doesn't work. First it says:

NameError: "name 'FirstName' is not defined"

Which is it's own problem… How do I tell it that FirstName is an attribute of the list I want it to sort?

Then I made FirstName a string just to try that…

AttributeError: "Student instance has no attribute 'sortby'"

Which I know there's no attribute sortby , that's supposed to be a parameter… but it can't use a parameter like that? Why not? How can I make it do this?

Python is actually looking for an attribute called 'sortby' which of course would not exist. Use the getattr builtin to fetch the attribute from the object using a string instead of the identifier.

def sort(sortlist, sortby):
    sortlist.sort(key = lambda x: getattr(x, sortby))

You can also use attrgetter from the operator module:

from operator import attrgetter
def sort(sortlist, sortby):
    sortlist.sort(key=attrgetter(sortby))

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