Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

function - Python question : The output will be method-type. How can I change the method type?

method return type is method. How can I change the method type. (self.get_sum, self.get_avg) <--- this is method type...??

class Student:
    def __init__(self, name, korean, math, english): #constructor
        self.name = name
        self.korean = korean
        self.math = math
        self.english = english

    def get_sum(self): #method
        return self.korean + self.math + self.english

    def get_avg(self): #method
        return self.get_sum / 4

    def to_str(self): #method
        return "{}{}{}".format(self.name, self.get_sum, self.get_avg)

students = [
        Student("a",55,55,55),
        Student("b",54,54,54),
        Student("c",53,53,53),
        Student("c",52,52,52)
]

print("name", "sum", "avg", sep = "")
for student in students:
    print(student.to_str())
question from:https://stackoverflow.com/questions/65560172/python-question-the-output-will-be-method-type-how-can-i-change-the-method-ty

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you need to call the functions so they execute and return a result. Currently your only passing a reference to the function not actually executing it. As a side note, your function for average seems to be off, your sum adds 3 values but your average divides by 4.....

class Student:
    def __init__(self, name, korean, math, english): #constructor
        self.name = name
        self.korean = korean
        self.math = math
        self.english = english

    def get_sum(self): #method
        return self.korean + self.math + self.english

    def get_avg(self): #method
        #return self.get_sum / 4
        return self.get_sum() / 4

    def to_str(self): #method
        #return "{}{}{}".format(self.name, self.get_sum, self.get_avg)
        return "{}{}{}".format(self.name, self.get_sum(), self.get_avg())

students = [
        Student("a",55,55,55),
        Student("b",54,54,54),
        Student("c",53,53,53),
        Student("c",52,52,52)
]

print("name", "sum", "avg", sep = "")
for student in students:
    print(student.to_str())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...