【问题标题】:How do I use getattr and setattr properly in Python? [closed]如何在 Python 中正确使用 getattr 和 setattr? [关闭]
【发布时间】:2015-04-24 19:38:08
【问题描述】:

我在 Python 中创建了一个名为 Student 的类。我需要创建该类的五个实例,然后能够从用户选择的实例中返回一个属性,并将一个属性设置为一个新值。这是我的代码:

class Student:

    # Initializer for Student Class
    def __init__(self):
        self.name = str(input("What is the name of the student? "))
        self.id_number = int(input("What is the i.d. number of " + self.name + "? "))
        self.gpa = float(input("What is " + self.name + "'s GPA? "))
        self.expected_grade = int(input("What is the expected grade of " + self.name + "? "))
        self.work_status = str(input("Does " + self.name + " work full-time or part-time? "))

    menu = str("1. Look up and print the student GPA." + '\n' +
               "2. Add a new student to the class." + '\n' +
               "3. Change the GPA of a student." + '\n' +
               "4. Change the expected grade of a student." + '\n' +
               "5. Print the data of all the students in a tabular format." + '\n' +
               "6. Quit the program. ")

    # Student list
    student_list = []

    # Print a list of the instances of Student in alphabetical order
    def display_students(self):
        Student.student_list.sort()
        print("")
        for n in Student.student_list:
            print(n)
        print("")

    # Print tabulated format of all instances of Student and attributes
    def display_student_info(self):
        Student.student_list.sort()
        print("Name\tI.D. #\t\tGPA\t\tExpected Grade\t\tEmployment")
        print("----------------------------------------------------------")
        for name in Student.student_list:
            print(name, '\t', getattr(name, "id_number"),
                  '\t', getattr(name, "gpa"), '\t', getattr(name, "expected_grade"), '\t', getattr(name, "work_status"))

    # Menu selection for user
    def menu_selection(self):
        valid_input = False
        user_input = int(input())
        while valid_input == False:
            try:
                if int(user_input) not in range(1, 6):
                    raise ValueError
                else:
                    valid_input = True
            except ValueError:
                print("You have entered an invalid selection for the menu. Please enter a number from 1 to 6. ")
                user_input = int(input(str()))
        # Look up and print student GPA
        if user_input == 1:
            Student.display_students(self)
            name = str(input("Which student would you like to look up the GPA for? "))
            print(name + ": " + getattr(Student.name, "gpa"))
        # Add a new student to the class
        if user_input == 2:
            print("")
            print("Okay. Let's add a new student to the class. ")
            Student.__init__(self)
            Student.student_list.append(Student.name)
        # Change the GPA of a student
        if user_input == 3:
            print("")
            print("Okay. Let's change the GPA of a student in the class.")
            self.display_students(Student)
            name = str(input("Which student's GPA would you like to change? "))
            new_gpa = str(input("What would you like " + name + "'s new GPA to be? "))
            setattr(Student.name, Student.gpa, new_gpa)
        # Change the expected grade of a student
        if user_input == 4:
            print("")
            print("Okay. Let's change the expected grade of a student.")
            print("Which student's expected grade would you like to change? ")
            self.display_students()
            name = str(input("Which student's expected grade would you like to change? "))
            new_expected_grade = float(input("What would you like " + name + "'s new expected grade to be? "))
            setattr(Student, str(Student.expected_grade), new_expected_grade)
        # Print the data of all the students in a tabular format
        if user_input == 5:
            print("")
            print("Okay, here is all the data for the currently entered students: ", '\n')
            Student.display_student_info(self)
        # Quit the program
        if user_input == 6:
            print("")
            print("Okay. Now quitting the program.")
            quit()


def main():

    count = 0
    while count < 5:
        Student.__init__(Student)
        Student.student_list.append(Student.name)
        print("")
        count += 1

    print("Now that the students information has been entered, you can select from the menu below to alter student data or quit the program."
          + '\n' + "Please make a selection: " + '\n')
    print(Student.menu)
    Student.menu_selection(Student)

main()

我的 getattr 或 setattr 方法无法正常工作。我怎样才能让他们工作?

【问题讨论】:

  • 你在哪里定义变量gpaexpected_grade?您了解变量的值和名称之间的区别吗?如果是这样,那么您需要的所有答案都在the documentation

标签: python getattr setattr


【解决方案1】:

getattrsetattr 的第二个参数是用于命名所需属性的字符串。即getattr(name, "expected_grade")。使用变量作为第二个参数意味着将变量的值用作名称。不过,一般来说,name.expected_gradegetattr(name, 'expected_grade') 之间没有真正的区别,尽管您可以提供 getattr 一个可选的第三个参数,如果命名属性不存在,则返回(而不是引发 AttributeError)。

您的代码中没有任何内容表明您需要getattrsetattr;只需使用点分名称语法来访问属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-05
    • 2011-10-17
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多