简体   繁体   English

Python __init__方法丢失了自我指针。 很奇怪

[英]Python __init__ method losing self pointer. Very strange

class RectangularRoom(object):
    """
    A RectangularRoom represents a rectangular region containing clean or dirty
    tiles.

    A room has a width and a height and contains (width * height) tiles. At any
    particular time, each of these tiles is either clean or dirty.
    """

    class Tile:
        def __init__(self,tilewidth,tileheight):
            self.tilewidth=tilewidth
            self.tileheight=tileheight
            self.isclean=false

    def __init__(self, initwidth,initheight):
        """
        Initializes a rectangular room with the specified width and height.

        Initially, no tiles in the room have been cleaned.

        width: an integer > 0
        height: an integer > 0
        """
        self.width=initwidth
        self.height=initheight
        self.tileslist=[]
        for i in range(self.width+1):
            for j in range(self.height+1):
                tileslist.add(Tile(i,j))

In the above code, in the line for j in range(self.height+1): , the self pointer is lost, as I found in pdb debugger 在上面的代码中,在for j in range(self.height+1):for j in range(self.height+1):self指针丢失了,正如我在pdb调试器中发现的那样

->for j in range(self.height+1):
(Pdb) p self
<ps2a.RectangularRoom object at 0x7f925c1d10d0>
(Pdb) s
NameError: "global name 'height' is not defined"
> <string>(1)<module>()->None
(Pdb) p self
*** NameError: NameError("name 'self' is not defined",)
(Pdb) $

I found that to be very strange (even alienlike). 我发现这很奇怪(甚至像外星人一样)。 Any thoughts? 有什么想法吗?

You changed your source code while running the script . 在运行脚本时更改了源代码。 Restart your Python session, the source and actual bytecode being run are out of sync. 重新启动Python会话,正在运行的源代码和实际字节码不同步。 This is why you get a NameError exception for a global name height , while your source code is using an attribute instead. 这就是为什么在源代码使用属性代替的同时,全局名称heightNameError原因。

Tools like pdb load the source code for listing lines on demand , while Python only loads the code once at the start, compiles it into bytecode and runs that. 诸如pdb之类的工具会按需加载用于列出行的源代码,而Python在开始时仅加载一次代码,然后将其编译为字节码并运行。 So you started with a line like for j in range(height+1): , started Python with that, saved a new version with self. 因此,您从for j in range(height+1):行开始,从此开始Python,并使用self.保存了一个新版本self. added, and then when you got to the loop in the debugger, pdb loaded that changed line from disk. 添加,然后在调试器中进入循环时, pdb从磁盘加载了更改的行。

Once the exception is thrown, you are dropped out of the __init__ method context; 引发异常后,您将退出__init__方法上下文; you are now at <string>(1)<module>()->None , not your for loop. 您现在位于<string>(1)<module>()->None ,而不是for循环。 There is no self local name in that scope. 在该范围内没有self本地名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM