您好我试图解决一个简单的问题,但我不知道如何迭代类实例i。即
class element :
def __init__(self, a, s, m):
self.name = a ;
self.symbol = s;
self.atomic_mass = m ;
class correction :
def __init__(self, a, atr, v):
self.name = a ;
self.atribute = atr;
self.correct_value = v ;
nitrogen = element("Nitrogen", "N", 12)
correction1 = correction("Nitrogen", "atomic_mass", 14)
我想做的就是找到一个" atomic_mass"在课堂上,如果有变化,我现在试图解决这个问题。
当然最终会有一个元素列表= [氮,碳,氦,氧等],我需要找到正确的元素并改变它的值。
到目前为止,我有这个:
def correct(elements, correction):
for i in elements:
for j in correction:
if i.a == j.a:
...
答案 0 :(得分:0)
您可以使用setattr()
内置方法。
例如:
class a:
def __init__(self, a: str, b: str):
this.a = a
this.b = b
inst = a("str1", "str2")
setattr(inst, "a", "new_string_1")
或只是inst.a = "new_string_1"
修改强>
hasattr
内置方法dir
内置方法 修改强>
最后,如果您有类列表,则可以编写校正方法,该方法采用元素列表和校正规则列表。例如:
correction_rules = [
{"attr": "atomic_mass", "search": 1, "change_to": 2},
{"attr": "Name", "search": 1, "change_to": 2}
]
def correct(objects, rules):
for obj in objects:
for rule in rules:
if hasattr(obj, rule["attr"]) and \
getattr(obj, rule["attr"]) == rule["search"]:
setattr(obj, rule["attr"], rule["change_to"])
correct(your_list_of_objects, correction_rules)
答案 1 :(得分:0)
感谢answear,我使用了setattr()并且它运行良好
def correct(elements, correction):
for i in elements:
for j in correction:
if i.a == j.a:
setattr(i,j.atr,j.v)