【问题标题】:Printing attributes from class/object files从类/对象文件打印属性
【发布时间】:2019-04-25 09:36:32
【问题描述】:

从编码能力的角度来看,我还处于“婴儿期”,我最近做了一个简单的类/对象上下文。不知道如何打印多个属性的详细信息,在这里寻求帮助。

在 Windows PC 上工作以尝试更明智地使用 Python 3,我创建了一个 student.py 和 object.py。前者包含 self.'s 而后者列出了 student1、student2....studentn 的实际特征。然而,我似乎只能为那个学生打印student1.gpastudent1.major 和其他一些学生特征。如何打印多个 student1 特征?

学生.py

class Student:

    def __init__(self, name, major, physicsLevel, mathLevel, chemistryLevel, gpa, is_on_probation):
        self.name = name
        self.physicsLevel = physicsLevel
        self.mathLevel = mathLevel
        self.chemistryLevel = chemistryLevel
        self.major = major
        self.gpa = gpa
        self.is_on_probation = is_on_probation

    def on_honor_roll(self): # function placed inside a class, in this case, whether student is on honor roll through the level of gpa
        if self.gpa >= 3.5:
            return True
        else:
            return False

object.py

from Student import Student

student1 = Student("Jim, ", "GeoPhysics and Space", "A", "A", "B", 3.1, "False")
student2 = Student("Ann, ", "Design and Innovation, ", "A, ", "A, ", "B", 4.2, "True")

问题:在下面尝试过,但没有更聪明的方法来打印所有学生或所有 gpa 成绩吗? - 另外,为什么第 2 行开始缩进一个字符,在下面尝试打印?

print(student1.name, student1.major, student1.physicsLevel, student1.gpa, '\r\n', student2.name, student2.major, student2.physicsLevel, student2.gpa)

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    在学生类中创建一个__str__ 方法,该方法返回一个具有您想要的格式的字符串:

    ....
    def __str__(self):
        return f"{self.name}, {self.major}, {self.gpa}"
    ...
    

    然后循环遍历学生:

    for student in (student1, student2):
        print(student)
    

    【讨论】:

    • 我可以在这里问一个新问题吗? - 因为我还想将 n 个学生写入 csv 文件?试图环顾四周,但我可能还没有聪明地理解我读到的建议,即结合上述类/对象上下文,然后将结果写入文件。谢谢,再次......;o)
    • @user11409667,你最好单独打开另一个问题。因为他们每个人都应该只涵盖一个特定的问题。
    猜你喜欢
    • 1970-01-01
    • 2020-08-28
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    相关资源
    最近更新 更多