【问题标题】:How to access values of a class from a different method(out the class)如何从不同的方法(类外)访问类的值
【发布时间】:2018-12-13 14:14:43
【问题描述】:

我有这种平静的代码,我试图在一个类中打印出一个字典,我如何从不同的方法访问值并指定要打印的值

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: 'Student' object has no attribute 'x'

【问题讨论】:

    标签: python class dictionary


    【解决方案1】:

    Student.student_instance_dict[student].x 将检查对象Student.student_instance_dict[student] 是否有一个名为x 的属性,而您的对象没有该属性。看起来您要做的是创建一个函数,该函数将获取名称作为字符串传入的属性的值。为此,请使用getattr():

    def printUpdates(x):
        print(getattr(Student.student_instance_dict[student], x))
    

    【讨论】:

    • 感谢您的解决方案示例和说明
    猜你喜欢
    • 2019-10-15
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多