我的代码如此宁静,我试图在一个类中打印出一个字典,如何从其他方法访问该值并指定要打印的值
class Student:
student_instance_dict = {}
def __init__(self, student):
self.name = None
self.phoneNumber = 0
students = ['Mike', 'Dany']
for student in students:
instance = Student(student)
Student.student_instance_dict[student] = instance
print (Student.student_instance_dict[student].name)#this prints out without any problems
def printUpdates(x):
print (Student.student_instance_dict[student].x)
name = 'name'
printUpdates(name)
las行返回AttributeError:“学生”对象没有属性“ x”
答案 0 :(得分:2)
Student.student_instance_dict[student].x
将在对象Student.student_instance_dict[student]
中检查名为x
的属性,而您的对象没有该属性。看起来您正在尝试创建一个函数,该函数将获取名称作为字符串传递的属性的值。为此,请使用getattr()
:
def printUpdates(x):
print(getattr(Student.student_instance_dict[student], x))