在类中正确使用字典的 getter/setter语言 - - 防止在设置字典元素时调用 getter



当我通过属性装饰器在类中设置字典的元素时,将调用@property getter。当我希望吸气剂对输出做一些事情时,这是一个问题。

背景

该主题与化学项目有关。

我想制作一个更具可读性和更易于访问的代码,而不是使用索引,eq。new = self.species['CO2'] * fractionself.species[14] * fraction更好

我也试过 字典值的 getter/setter 的正确用法 但它不能解决二传手/吸气手问题。

目前,我通过禁用getter,定义一个get_dict函数并仅允许设置整个字典来解决此问题。

但是使用这种方法,我不能简单地循环通过数组(dictA:dictnew_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)

你关于"二传手叫吸盘手"的观察是错误的,但我明白它来自哪里。

test.propA会称examplepropA。不是因为"二传手调用getter"(坦率地说,这3行甚至没有调用二传手(,而仅仅是因为test.propA需要先获取底层字典,然后才能调用其__setitem__方法。

这里唯一"真正"的解决方案是更好的设计,就像我在评论中建议的那样。您可以在example中编写一个包装器方法,该方法将项目直接设置在_propA上,但这就像跳过围栏而不是穿过前门一样。

最新更新