[英]A better way to call Class Methods from List of Class Objects - Python
I was working on Python Classes and found that one cannot call class method from class object by looping through a list of such objects.我正在研究 Python 类,发现无法通过循环遍历此类对象的列表来从类对象调用类方法。 Below is a sample code:下面是一个示例代码:
def show_student_details(*s_list):
for s in s_list:
print("Roll Number: ", s.get_roll_no())
print("Name: ", s.get_name())
print("Phone: ", s.get_phone())
print("Marks: ", s.get_marks())
The code for Student class is: Student 类的代码是:
class Student:
def __init__(self, roll_no=0, name="", phone="", marks=-1):
self.__roll_no = roll_no
self.__name = name
self.__phone = phone
self.__marks = marks
def get_roll_no(self):
return self.__roll_no
def get_name(self):
return self.__name
def get_phone(self):
return self.__phone
def get_marks(self):
return self.__marks
Running this piece of code by passing some objects of Student class gives the following error:通过传递 Student 类的一些对象来运行这段代码会出现以下错误:
File "main.py", line 88, in <module>
show_student_details(students)
File "main.py", line 12, in show_student_details
print("Roll Number: ", s.get_roll_no())
AttributeError: 'list' object has no attribute 'get_roll_no'
The thing I understand is that List
is itself a Class and Python interprets this code as if I was calling the get_roll_no()
function on List Object.我的理解是List
本身就是一个类,Python 解释这段代码就像我在 List 对象上调用get_roll_no()
函数一样。
I googled this problem and found that map()
and methodcaller()
can be used to call the class methods but they didn't work for me.我在 google 上搜索了这个问题,发现map()
和methodcaller()
可用于调用类方法,但它们对我不起作用。
I know that this question has been asked multiple times on StackOverflow but I think none of them solved my problem which is ' calling multiple class methods from object by selecting objects one by one from a list of class objects.我知道这个问题在 StackOverflow 上被问过多次,但我认为他们都没有解决我的问题,即“通过从类对象列表中一个一个地选择对象来从对象调用多个类方法。 ' '
Any help will be appreciated.任何帮助将不胜感激。 Thanks in Advance.提前致谢。
Assuming you are passing a list of students to the function such as ([<__main__.Student object at 0x122d85990>, <__main__.Student object at 0x122d85910>],)
, you can use :假设您将学生列表传递给函数,例如([<__main__.Student object at 0x122d85990>, <__main__.Student object at 0x122d85910>],)
,您可以使用:
def show_student_details(*s_list):
for s in s_list[0]:
print("Roll Number: ", s.get_roll_no())
print("Name: ", s.get_name())
print("Phone: ", s.get_phone())
print("Marks: ", s.get_marks())
Because *s_list converts your input to a list.因为 *s_list 会将您的输入转换为列表。 Alternatively, you should be able to just use或者,您应该可以只使用
def show_student_details(s_list):
for s in s_list:
print("Roll Number: ", s.get_roll_no())
print("Name: ", s.get_name())
print("Phone: ", s.get_phone())
print("Marks: ", s.get_marks())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.