【问题标题】:Is an assigned value not always a variable? [closed]赋值不总是变量吗? [关闭]
【发布时间】:2021-02-09 07:23:39
【问题描述】:

我正在尝试在 Pycharm 中调试一些 Python3.8 代码。

代码最初分配的值如下所示:

self.stats.game_active = False

游戏启动后,修改如下:

self.stats.game_active = True

当我运行调试器时,我看不到当前值是 True 还是 False,因为我没有看到变量列表中的值。

我找错地方了吗?我以为我正在使用一个变量。我不是吗?如果它不是变量,它叫什么?如果它是一个变量,我如何让它显示在调试器的变量列表中?

克利波维奇

其他可能有用的信息:

class GameStats:
    """Track statistics for Alien Invasion."""

    def __init__(self, ai_game):
        """Initialize statistics."""
        self.settings = ai_game.settings
        self.reset_stats()

        # Start Alien Invasion in an inactive state.
        self.game_active = False

def __init__(self):
    """Initialize the game and create game resources."""
    pygame.init()
    self.settings = Settings()

    # Create an instance to store game statistics
    self.stats = GameStats(self)



 def _start_game(self):
        # Reset the game statistics.
        self.stats.reset_stats()
        self.stats.game_active = True

【问题讨论】:

  • 你能把它变成一个small的例子吗?这一行在一个方法中,并且该方法是在一个类上定义的。在某个地方创建类,然后调用该方法。可以说那行是my_instance.some_method()。然后你会看到变量为my_instance.stats.game_active
  • self 是这里的变量。它可能是一个包含stats 属性的对象,该属性又包含game_active 属性。您需要进行一些深入研究才能在调试器中获取此值。
  • 我在原始帖子中添加了其他代码。希望对您有所帮助。
  • 那么“self”是我需要在变量名中寻找的吗?

标签: python variables debugging pycharm


【解决方案1】:

您是否尝试将变量添加到观察列表?

据我所知,这应该可以让您始终看到变量的值。

-在 Watches 窗格中,单击 New Watch 按钮 New Watch 或按 Insert。

-在“变量”窗格中选择一项或多项并将它们拖到“监视”窗格中。

-右键单击编辑器中的项目并选择添加到手表。

【讨论】:

  • 我试过了,但我不确定我在找什么。我试图找到 self.stats.game_active 但调试器说它不是一个变量。 @jasonharper 说我应该寻找“自我”。我想我在寻找一个太长的名字。我有几个“自我”的例子。我会尝试找出如何隔离其中一个。
  • @chadrick self 仅在变量在范围内时定义。如果您将调试器单步执行到通常以self 作为参数的类实例方法中,那么只有这样它才会被定义并且对调试器可见。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-10
  • 2014-09-10
  • 2011-01-18
  • 2014-10-31
  • 1970-01-01
  • 2018-03-13
  • 2022-01-20
相关资源
最近更新 更多