当我通过属性装饰器在类中设置字典的元素时,将调用@property getter。当我希望 getter 对输出执行某些操作时,这是一个问题。
背景
该主题与化学项目相关。
我想制作一个更具可读性和更易于访问的代码,而不是使用索引,例如。 new = self.species['CO2'] *fraction
比 self.species[14] *fraction
我也尝试过 Correct usage of a getter/setter for dictionary values 但它不能解决setter/getter问题。
目前,我通过禁用 getter、定义 get_dict 函数并只允许设置整个字典来解决这个问题。
但是通过这种方法,我不能简单地通过数组循环(dictA:dict
和 new_values:numpy array
):
for i,value in enumerate(dictA):
dictA[value] = new_values[i]
运行示例
class example():
def __init__(self):
self._propA = {'A':1,'B':0,'C':0}
@property
def propA(self):
print('Getter')
return normalize_dict(self._propA)
@propA.setter
def propA(self,propB:dict):
print('Setter')
match = list(set(propB).difference(self._propA))
if match:
raise ValueError('{match} is/are not part of the required input: {listing}'.format(match=match,listing=list(self._propA.keys())))
else:
for i,value in enumerate(propB):
self._propA[value] = propB[value]
return self._propA
支持代码
def normalize_dict(inquiry: dict):
inquiry_new = {}
try:
for i,value in enumerate(dict(inquiry)):
inquiry_new[value] = inquiry[value]
except TypeError:
error_string = 'Not a dictionary type class!'
raise TypeError(error_string)
for i,(valA,valB) in enumerate(inquiry_new.items()):
if type(valB)!=float and type(valB)!=int:
raise ValueError(valB,'is not a number')
if float(valB) < 0:
print ('Input is negative. They are ignored!')
continue
sum = 0
for i,(valA,valB) in enumerate(inquiry_new.items()):
if valB < 0:
valB = 0
sum += valB
for i,(valA,valB) in enumerate(inquiry_new.items()):
inquiry_new[valA] = valB/sum
return inquiry_new
结果
main.py
:
test = example()
test.propA = {'A':5,'B':4,'C':1}
print(test.propA)
test.propA = { 'A':1 }
test.propA = { 'B':5 }
test.propA = { 'C':4 }
print(test.propA)
test.propA['A'] = 5
test.propA['B'] = 4
test.propA['C'] = 1
print(test.propA)
输出
Setter
Getter
{'A': 0.5, 'B': 0.4, 'C': 0.1}
Setter
Setter
Setter
Getter
{'A': 0.1, 'B': 0.5, 'C': 0.4}
Getter
Getter
Getter
Getter
{'A': 0.1, 'B': 0.5, 'C': 0.4}
想要的输出
Setter
Getter
{'A': 0.5, 'B': 0.4, 'C': 0.1}
Setter
Setter
Setter
Getter
{'A': 0.1, 'B': 0.5, 'C': 0.4}
Setter
Setter
Setter
Getter
{'A': 0.5, 'B': 0.4, 'C': 0.1}
问题
正如您从输出中看到的,调用的是“Getter”而不是“Setter”。
最佳答案
这里没有任何问题,您得到的输出非常有意义。
您在实际输出中看到了这一点:
Getter
Getter
Getter
Getter
{'A': 0.5, 'B': 0.4, 'C': 0.1}
由于示例中的这些行:
test.propA['A'] = 5
test.propA['B'] = 4
test.propA['C'] = 1
print(test.propA)
您关于“setter 调用 getter”的观察是错误的,但我明白它的来源。
test.propA
会打电话example
的propA
setter/getter 。不是因为“setter 调用 getter”(坦率地说,setter 甚至没有被这 3 行调用),而仅仅是因为 test.propA
需要先获取底层字典,然后才能调用其 __setitem__
方法。
这里唯一的“真正”解决方案是像我在评论中建议的那样更好的设计。您可以在 example
中编写一个包装方法这将直接在 _propA
上设置项目但这就像跳过栅栏而不是穿过前门。
关于python - 类中字典的 getter/setter 的正确用法——防止在设置字典元素时调用 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048363/