【问题标题】:How to use dictionary in Python correctly如何在 Python 中正确使用字典
【发布时间】:2023-03-08 05:03:01
【问题描述】:

Python 字典一直让我感到困惑。

我有 3 个字典:

left_dict = {"N":"W", "W":"S", "S":"E", "E":"N"}
right_dict = {"N":"E", "E":"S", "S":"W", "W":"N"}
turn_dict = {"N":"S", "E":"W", "S":"N", "W":"E"}

我有一个机器人类,它是这样初始化的:

class Robot:
    def __init__(self, team, x, y, direction):
        self.team = team
        self.health = 50
        self.x = x     
        self.y = y
        self.direction = direction

在这个类中,我有一个改变方向的方法。

def left90(self):
        self.direction = left_dict <---- **is this how I would change the direction**

【问题讨论】:

  • 我创建了字典......这是我不知道该怎么做的实现。我知道它们的用途..它们是如何使用的我不知道该怎么做。
  • 我只是在问最后一行是否是正确的使用方法。

标签: python class python-2.7 dictionary


【解决方案1】:

我相信您正在寻找的是:

def left90(self):
    self.direction = left_dict[self.direction]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-21
    • 2015-04-12
    • 2021-12-31
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多