简体   繁体   中英

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}.

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.

However, 3.8 does not print to console, rather <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()

Does this mean I have to convert the output of gpa.Student into a string?

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:

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:

@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. You could reinstate it if you need it there for some other reason.

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