简体   繁体   English

如何在函数Python中调用类

[英]How to call a class in a function Python

I'm a complete amateur, and trying to work out how to write a function that takes a list of objects, and returns a list of the names of said objects (based on whether they pass if statement). 我是一个完全的业余爱好者,并试图找出如何编写一个获取对象列表的函数,并返回所述对象的名称列表(基于它们是否通过if语句)。 This is the class I've written from help of tutorials: 这是我从教程的帮助中编写的课程:

class Student:  
passmark=50  

def __init__(self,name,mark):  
    self.name=name  
    self.mark=mark  

def passes(self):  
    return self.mark > Student.passmark 

So from now I'm assuming I make a list of objects, say: 所以从现在起我假设我列出了一些对象,比如说:

students = []  

Though this list is just a brand new list, which was necessary sure but how would I link it to the class? 虽然这个列表只是一个全新的列表,但这是必要的,但我如何将它链接到班级呢? From this point I want to find out which students have failed, and return them and also where I am confused: 从这一点开始,我想找出哪些学生失败了,然后回复他们以及我感到困惑的地方:

def failed(list):  
    for student in Students:  
        if passmark > self.mark:  
            return list  

Is all I can muster, sorry I've just gotten to classes and calling classes is quite confusing for me. 我只能鼓起勇气,对不起,我刚刚上课,打电话给我很困惑。 The above code doesn't reference the class at all, and I really am confused on how to do so. 上面的代码根本没有引用该类,我真的很困惑如何这样做。 I've no syntax errors or anything, I think my logic is fatally flawed. 我没有语法错误或任何东西,我认为我的逻辑存在致命缺陷。

You want to take all the student from the students list. 你想从学生名单中取出所有学生。 So use that in the for loop. 所以在for循环中使用它。 Also, you correctly encapsulated the logic of pass/fail criteria in a method, so use that. 此外,您正确地在方法中封装了通过/失败条件的逻辑,因此请使用它。

Here is the code I think will do want you want: 这是我认为你想要的代码:

def failed(list_of_students):
   failed_students = []
   for student in list_of_students:  
       if not student.passes():  
           failed_students.append(student.name)  
   return failed_students

A more advanced way of doing it is by using list comprehension: 更高级的方法是使用列表理解:

def failed(list_of_students):
    return [student for student in list_of_students if not student.passes()]

It is more pythonic, but my be harder to understand for a beginner with a C or Java background. 它更加pythonic,但对于具有C或Java背景的初学者来说,我更难理解。

You can use a list comprehension like this: 你可以使用这样的列表理解:

def failed(list):
    return [student.name for student in students if not student.passes()]

Try this code. 试试这个代码。 Using list comprehension to return results. 使用列表推导返回结果。 It's a very powerful python tool. 这是一个非常强大的python工具。

class Student:  
    passmark = 50
    def __init__(self, name, mark):  
        self.name=name  
        self.mark=mark  

    def passes(self):  
        return self.mark > Student.passmark 

    def __repr__(self):
        return '{} {}'.format(self.name, self.mark)


def failed(students_list):  
    return [student for student in students_list if student.mark < Student.passmark]

Given a Student class like you defined: 鉴于您定义的Student类:

class Student:  
    passmark=50  

    def __init__(self,name,mark):  
        self.name=name  
        self.mark=mark  

    def passes(self):  
        return self.mark > Student.passmark 

You could instantiate a list of students with: 您可以通过以下方式实例化学生列表:

students = [Student("John", 49), Student("Mary", 75)]

It looks like you are also trying to define a function that will return a list of all the failed students; 您似乎也在尝试定义一个函数,该函数将返回所有失败学生的列表; you could do something like this: 你可以这样做:

def failed(student_list):
    return [x for x in student_list if not x.passes()]
mark_to_pass = 50

#Approach one
class Student:
    def __init__(self, student_name, student_mark):
        self.name = student_name
        self.mark = student_mark
        self.pass_mark = self.calculate_passing_mark(mark_to_pass)

    def calculate_passing_mark(self, mark_to_pass):
        if self.mark >= mark_to_pass:
            return True
        return False

if __name__ == '__main__':
    example_student = Student("Swanson", 75)
    print(example_student.pass_mark)

With this approach every time a student object is created it will tell create a field telling you that student has passed. 每次创建学生对象时,都会使用此方法创建一个告诉您学生已通过的字段。 When working with lists such as a list of student objects you need to add the student to your list. 使用列表(例如学生对象列表)时,您需要将学生添加到列表中。 Example

students = []
students.append(example_student)

Now you can look through your student list by doing 现在,您可以通过查看学生列表

for student in students:
   print(student.pass_mark) # or do some other logic passed on who passed or failed. Or even here you dont need to create pass_mark object you can just check if student.mark > pass_mark

I'm assuming that failed isn't a member function of the class Student. 我假设失败不是Student类的成员函数。 The below code should work for what you are trying to do. 以下代码应该适用于您要执行的操作。

class Student:
    passmark=50
    def __init__(self,name,mark):
        self.name=name
        self.mark=mark  

    def passes(self):  
         return self.mark > Student.passmark

students = [Student("tom",40),Student("joe",70)]

def failed(listofStudents):
    listofStudentsThatFail = []
    for student in listofStudents:
        if not student.passes():
            listofStudentsThatFail.append(student)
    return listofStudentsThatFail

for s in failed(students):
    print s.name

The ouput when you run the code is: tom 运行代码时的输出是:tom

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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