在下面的代码中,我如何更改set_ref方法,使其自动更改为引用键的值,以匹配每次打印表单时引用的键的值?
例如:
在下面的代码中,我将A1的值设置为10,然后我使用set_ref方法使A3引用A1,因此它也是10。现在,当我把A1的值设为20时,A3仍然是10。我需要做什么才能自动将A3值更改为20?
#create sheets class with constructor to initialize "cells" instance variable as a dictionary
class Sheet:
def __init__(self) -> None:
self.cells = dict()
# set_value method takes key as a string and value as an int, set cells with
# key index along with its value
def set_value(self, key: string, value: int) -> None:
self.cells[key] = value
# get_value method takes the key as a string and return the value of the cell
# based on key index
def get_value(self, key: string) -> int:
return self.cells[key]
# set ref takes new key, the reference key and the old key, the key being referenced
# use set value method to set new value that has new key and the value of the key that it references
def set_ref(self, ref_key: string, key:string):
self.set_value(ref_key, self.cells[key])
# repr dunder method returns output as a string
# for each key in all the cells:
# add to the output= key: and its value and return key:value pair to us
def __repr__(self):
output = "--------n"
for key in self.cells.keys():
output += f'{key}: {self.get_value(key)}n'
output += "--------"
return output
# sheet object instantiation
sheet = Sheet()
sheet.set_value('A1', 10)
sheet.set_ref('A3', 'A1')
print(sheet) # A3 is now 10, just like A1
sheet.set_value('A1', 20)
print(sheet) # A3 is still 10, not 20
假设键总是str
,值总是int
,你可以稍微调整一下你的代码:
class Sheet:
def __init__(self) -> None:
self.cells = dict()
# set_value method takes key as a string and value as an int, set cells with
# key index along with its value
def set_value(self, key: str, value: int) -> None:
self.cells[key] = value
# get_value method takes the key as a string and return the value of the cell
# based on key index
def get_value(self, key: str) -> int:
if type(self.cells[key]) == int:
return self.cells[key]
return self.get_value(self.cells[key])
# set ref takes new key, the reference key and the old key, the key being referenced
# use set value method to set new value that has new key and the value of the key that it references
def set_ref(self, ref_key: str, key:str):
self.set_value(ref_key, key)
# repr dunder method returns output as a string
# for each key in all the cells:
# add to the output= key: and its value and return key:value pair to us
def __repr__(self):
output = "--------n"
for key in self.cells.keys():
output += f'{key}: {self.get_value(key)}n'
output += "--------"
return output
# sheet object instantiation
sheet = Sheet()
sheet.set_value('A1', 10)
sheet.set_ref('A3', 'A1')
print(sheet) # A3 is now 10, just like A1
sheet.set_value('A1', 20)
print(sheet)
输出:
--------
A1: 10
A3: 10
--------
--------
A1: 20
A3: 20
--------
方法签名保持不变。
我们现在设置了两种类型的值:值本身(int
)或ref (str
)。
秘密是当接收到值(get_value
)时:我们检查值的类型;如果是int
,那就是最终值。否则,使用存储在该单元格中的键递归调用get_value
.