【发布时间】:2021-02-16 15:19:58
【问题描述】:
我正在尝试在 Student 类中创建一个函数来搜索动态创建的属性。我找不到使用 函数 export_rubric_inputs(self, rubric) 的参数来调用字典键的方法。请注意,该属性将是从 save_rubric_inputs 函数创建的字典。
我尝试了很多不同的方法,包括使用 getattr,但因为它是一本字典,所以它不起作用。
编辑:我想使用导入功能访问我作为字典存储的数据
代码:
#Example Dictionary
collector_card = {
"name": "collector_card",
1: "x",
5: 3,
7: "You are correct"
}
*Metaclass: Makes a class iterable*
class IterRegistry(type):
def __iter__(cls):
return iter(cls._registry)
*Creates instances of students when imported from CSV File*
class Student(metaclass=IterRegistry):
*Keeps Track of all instances of Class*
_registry = []
*Constructor*
def __init__(self, name, student_id = 0):
self._registry.append(self)
self.student_id = student_id
self.name = name
*Takes inputs after created in Tkinter*
def save_rubric_inputs(self, rubric):
setattr(self, rubric["name"], rubric)
*What I am having trouble with*
def export_rubric_inputs(self, rubric):
self.rubric
# Creating a Single Instance for this example
dave = Student("Dave")
dave.save_rubric_inputs(collector_card)
dave.export_rubric_inputs(collector_card)
【问题讨论】:
-
你想让
export_rubric_inputs返回save_rubric_inputs中设置的属性吗? -
请展示您希望如何使用您的代码,例如通过包含代码 sn-p 以及该 sn-p 的预期输出。
-
@SaedSayedAhmed 是的,完全正确
-
*有什么用?另外,你能提供一个minimal reproducible example吗? -
@AMC 这是我第一次在这里提出问题,而# 正在做奇怪的事情。我确实在最后添加了一个小例子。下面的答案确实有效,我只是不明白为什么,因为它似乎引用了字典的一部分。我把完整的评论放在下面