python-3.x - 访问类的属性不起作用?
问题描述
我在方法上写了一个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.
解决方案
这是你需要的吗?:
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)
推荐阅读
- excel - 我怎样才能让这段代码在后台安静地运行?
- python - Calling Custom Lambda Layers Functions on Lambda
- java - Android为onClick事件划分多个区域的图像
- mysql - 如何在 NiFi PUTSQL 中运行 SQL 更新查询?
- python-3.x - 使用 Python3 Pytesseract 进行实时屏幕监控
- angular - Angular-reactive 表单输入字段的条件正则表达式
- sqlite - Sqlite 总和时间
- python - 原理图python列表中的多个对象
- google-my-business-api - 尝试查询帐户时在 Google My Business API 上找不到方法
- go - 里面有不同结构的结构切片