[英]Print method output as a string, not as a function
In my Student subclass below, I am calculating average GPA from manually inputted grades stored in the self.courses
dict attribute as {course:grade}. 在下面的“学生”子类中,我根据手动输入的存储在self.courses
dict属性中的self.courses
({course:grade})计算平均GPA。
The user should be able to enter in the console >>>print(fred.gpa),given fred is a proper Student instance with grades in self.courses
, and should get 3.8
(for example) printed to the console. 用户应该能够在控制台中输入>>> print(fred.gpa),因为fred是在self.courses
具有等级的适当Student实例,并且应该获得3.8
(例如)打印到控制台。
However, 3.8
does not print to console, rather <bound method Student.gpa of <college.Student object at 0x7ff55e122ad0>>
但是, 3.8
不会打印到控制台,而是打印到<bound method Student.gpa of <college.Student object at 0x7ff55e122ad0>>
I understand that this is the result of printing a function, but I want to print just a number using just print(fred.gpa) and not fred.gpa() 我知道这是打印函数的结果,但是我只想使用print(fred.gpa)而不是fred.gpa()来打印数字。
Does this mean I have to convert the output of gpa.Student into a string? 这是否意味着我必须将gpa.Student的输出转换为字符串?
Here is my code for ref: 这是我的参考代码:
def __init__(self, name, cid, email):
self.courses = {}
super().__init__(name, cid, email)
def add_course(self, course):
if course in self.courses:
# duplicate courses not allowed
raise ValueError
print("student is already registered for this course")
else:
self.courses.update({course:0})
return self
def update_grade(self, course, grade):
if course not in self.courses:
# student must be registered in class to receive grade
raise ValueError
print("student is not registered for this course")
else:
self.courses[course] = float(grade)
return self
def gpa(self):
grades = list(self.courses.values())
totGPA = sum(grades)/len(grades)
return str(totGPA)
What you need is something that will let you implement something as a method, but access it as a non-method attribute. 您需要的是使您可以将某些方法实现为一种方法,但将其作为非方法属性来访问的方法。 That turns out to be quite easy - it's called a property
, and it works like this: 事实证明,这很容易-称为property
,其工作方式如下:
class Student:
@property
def gpa(self):
# Rest of the implementation, unchanged
Ta-da! 当当!
Note that you can fix up your implementation of gpa
a little: sum
can take any iterable (it doesn't have to be a list), and dicts (and their keys
, values
and items
views) have a length, so you can do: 请注意,您可以稍微修正一下gpa
的实现: sum
可以采用任何可迭代的方式(不必是列表),而dict(及其keys
, values
和items
视图)具有长度,因此您可以:
@property
def gpa(self):
return sum(self.courses.values())/len(self.courses)
I've omitted your call to str
, since it seems from your question that that was a first attempt to fix your problem. 我已经省略了您对str
的调用,因为从您的问题来看,这似乎是解决您的问题的第一次尝试。 You could reinstate it if you need it there for some other reason. 如果出于其他原因在此处需要它,可以将其恢复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.