【问题标题】:Accessing the attribute of a class not working?访问类的属性不起作用?
【发布时间】:2020-05-25 17:34:16
【问题描述】:

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

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.x error-handling


    【解决方案1】:

    这是你需要的?:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多