如何重构Python“switch 语句”

发布于 2024-12-03 23:55:05 字数 1062 浏览 1 评论 0原文

我正在重构一位朋友编写的一些代码,最近偶然发现了这个函数:

def setup_parameters(self, data):
    '''Parse raw data to determine game settings.'''
    for line in data.split('\n'):
      line = line.strip().lower()
      if line:
        tokens = line.split()

        self.L.debug("tokens: " + str(tokens))

        key = tokens[0]
        if key == 'cols':
          self.width = int(tokens[1])
        elif key == 'rows':
          self.height = int(tokens[1])
        elif key == 'player_seed':
          random.seed(int(tokens[1]))
        elif key == 'turntime':
          self.turntime = int(tokens[1])
        elif key == 'loadtime':
          self.loadtime = int(tokens[1])
        elif key == 'viewradius2':
          self.viewradius2 = int(tokens[1])
        elif key == 'attackradius2':
          self.attackradius2 = int(tokens[1])
        elif key == 'spawnradius2':
          self.spawnradius2 = int(tokens[1])

如您所见,这里有一种令人讨厌的 switch 语句,它显然需要字典。我很想将其写为类字典,因为键是不变的,但由于键映射到实例的属性(即“cols”:self.width),因此无法编译。

那么我的问题是,重构此类代码的正确方法是什么?

I'm refactoring some code that a friend wrote and recently stumbled across this function:

def setup_parameters(self, data):
    '''Parse raw data to determine game settings.'''
    for line in data.split('\n'):
      line = line.strip().lower()
      if line:
        tokens = line.split()

        self.L.debug("tokens: " + str(tokens))

        key = tokens[0]
        if key == 'cols':
          self.width = int(tokens[1])
        elif key == 'rows':
          self.height = int(tokens[1])
        elif key == 'player_seed':
          random.seed(int(tokens[1]))
        elif key == 'turntime':
          self.turntime = int(tokens[1])
        elif key == 'loadtime':
          self.loadtime = int(tokens[1])
        elif key == 'viewradius2':
          self.viewradius2 = int(tokens[1])
        elif key == 'attackradius2':
          self.attackradius2 = int(tokens[1])
        elif key == 'spawnradius2':
          self.spawnradius2 = int(tokens[1])

As you can see, there is a nasty kind of switch statement here, that clearly calls for a dictionary. I'm tempted to write this as a class dictionary since the keys are constant, but since the keys map to attributes of an instance (ie, 'cols': self.width) this doesn't compile.

My question is then, what is the right way to refactor such code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

怀中猫帐中妖 2024-12-10 23:55:05

将键映射到属性的名称,并使用setattr(self, attribute_name, int(tokens[1]) 设置值。例如:

attribute_dict = dict(cols="width", rows="height", turntime="turntime", ...)
[...]
value = int(tokens[1])
if key == "player_seed":
    random.seed(value)
else:
    setattr(self, attribute_dict[key], value)

Map the keys to the names of the attributes, and use setattr(self, attribute_name, int(tokens[1]) to set the value. E.g.:

attribute_dict = dict(cols="width", rows="height", turntime="turntime", ...)
[...]
value = int(tokens[1])
if key == "player_seed":
    random.seed(value)
else:
    setattr(self, attribute_dict[key], value)
囚我心虐我身 2024-12-10 23:55:05

您可以构建一个字典,其中键作为访问器,并使用 lambda 函数来执行每个键的代码。

You can build up a dictionary with the keys as accessors and lambda functions to execute the code for each key.

拥抱我好吗 2024-12-10 23:55:05

使用以下操作设置一个字典

actions = dict(cols = lambda tokens: setattr(self, "width", int(tokens[1]), ... 
               player_seed = lambda tokens: random.seed(int(tokens[1]))
              )

 actions[key](tokens)

setup a dict with actions like

actions = dict(cols = lambda tokens: setattr(self, "width", int(tokens[1]), ... 
               player_seed = lambda tokens: random.seed(int(tokens[1]))
              )

and then:

 actions[key](tokens)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文