【问题标题】:Python question : The output will be method-type. How can I change the method type?Python 问题:输出将是方法类型。如何更改方法类型?
【发布时间】:2021-04-10 02:21:25
【问题描述】:

方法返回类型是方法。如何更改方法类型。 (self.get_sum, self.get_avg)

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 "{}\t{}\t{}".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 = "\t")
for student in students:
    print(student.to_str())

【问题讨论】:

  • 您没有调用方法,只是传递了它们的引用。你应该改成return "{}\t{}\t{}".format(self.name, self.get_sum(), self.get_avg())
  • 告诉我如何改变
  • 我在评论中向您展示了要更改的内容。您需要调用函数以便它们返回结果,目前您只是将引用传递给函数
  • 当你调用一个方法时,你需要括号 - 在第 12 行和第 15 行..
  • 天哪~~非常感谢~~^^

标签: python-3.x function methods


【解决方案1】:

您需要调用函数以便它们执行并返回结果。目前,您只传递对函数的引用,而不是实际执行它。作为旁注,您的平均值函数似乎已关闭,您的总和增加了 3 个值,但您的平均值除以 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 "{}\t{}\t{}".format(self.name, self.get_sum, self.get_avg)
        return "{}\t{}\t{}".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 = "\t")
for student in students:
    print(student.to_str())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    相关资源
    最近更新 更多