【发布时间】:2019-12-20 18:42:15
【问题描述】:
预脚本:我已经搜索了很多关于 SO 的线程,但似乎没有人回答我的问题。
我制作了一个小脚本,它处理一个在网格周围移动的点,同时用它遍历的所有点更新一个集合。 move() 方法的要点是:
# self.x and self.y are initialised to 0 at the time of object creation
# dir_ - direction in which to move
# steps - number of steps to move
def _move(self, dir_, steps):
if dir_ == 'U':
for step in range(steps):
self.y += 1
self.locations.add((self.x, self.y))
elif dir_ == 'R':
for step in range(steps):
self.x += 1
self.locations.add((self.x, self.y))
elif dir_ == 'L':
for step in range(steps):
self.x -= 1
self.locations.add((self.x, self.y))
elif dir_ == 'D':
for step in range(steps):
self.y -= 1
self.locations.add((self.x, self.y))
else:
raise Exception("Invalid direction identifier.")
如您所见,有很多重复。在我渴望清理东西的过程中,我尝试了这样的事情:
from operator import add, sub
def _move(self, dir_, steps):
dir_dict = {'U': (self.y, add), \
'D': (self.y, sub), \
'L': (self.x, sub), \
'R': (self.x,add)}
coord, func = dir_dict[dir_]
for step in range(steps):
coord = func(coord, 1)
locations.add(self.x, self.y)
事实证明,我不能期望像这样传递对象属性的引用,因此self.x 和self.y 没有更新。
问题:
如何清理这段代码以避免重复?
即使原始代码段被认为对功能“没有那么糟糕”,是否有办法按照我的意图传递实例属性?
【问题讨论】:
-
dir_dict = {'U': (0, 1), 'D': (0, -1), ... } -
这如何告诉我要更新哪个属性?
-
你更新both。
-
哦,好的,我明白了。谢谢。在某些方面,我发现这种清洁剂。 P.S.:我认为,如果您指出您在元组中表示的内容与 OP 中提到的内容不同,那将会很有帮助。 :)
标签: python dictionary oop attributes instance