gpt4 book ai didi

python - 使用实例属性作为字典值

转载 作者:行者123 更新时间:2023-11-30 21:54:02 25 4
gpt4 key购买 nike

前言:我已经搜索了很多关于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.xself.y 未更新。

问题:

  1. 如何清理此代码以避免重复?

  2. 即使原始代码片段的功能被认为“并不是那么糟糕”,是否有办法以我想要的方式传递实例属性?

最佳答案

您的第一次重构绝对是在正确的轨道上。您看到的问题是 addsub 返回新值,而不是现有值。 coordself.xself.y 不同。我将在这里使用属性查找

from operator import add, sub

def _move(self, dir_, steps):
dir_dict = {'U': ('y', self.y, add), \
'D': ('y', self.y, sub), \
'L': ('x', self.x, sub), \
'R': ('x', self.x, add)}

attr, coord, func = dir_dict[dir_]
for step in range(steps):
coord = func(coord, 1)
# set the attribute on self here
setattr(self, attr, coord)
locations.add(self.x, self.y)

关于python - 使用实例属性作为字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59429983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com