首页 > 解决方案 > 访问类的属性不起作用?

问题描述

我在方法上写了一个Question带有三个参数的类__init__。但是当我尝试打印属性时,代码会引发属性错误。

class Question:

    def __init__(self, question, ca, cb, cc, cd, correct_choice):
        self.__question = question
        self.__choice_a = ca
        self.__choice_b = cb
        self.__choice_c = cc
        self.__choice_d = cd
        self.__correct = correct_choice


# Create instances
q1 = Question(
        'What is the square root of 622521?',
        789, 790, 791, 792,
        'a'
)
**print(q1.__choice_d)**      # This part of the code raises an attribute error.

标签: python-3.xerror-handling

解决方案


这是你需要的吗?:

class Question:

    def __init__(self, question, ca, cb, cc, cd, correct_choice):
        vars(self)['__question'] = question
        vars(self)['__choice_a'] = ca
        vars(self)['__choice_b'] = cb
        vars(self)['__choice_c'] = cc
        vars(self)['__choice_d'] = cd
        vars(self)['__correct'] = correct_choice

# Create instances
q1 = Question(
        'What is the square root of 622521?',
        789, 790, 791, 792,
        'a'
)

print(q1.__choice_d)

推荐阅读