1

我正在阅读一些 wxPython 代码来学习一些 Python。请记住,我真的是一个初学者,所以我的问题对你来说很明显,但对我来说,这很神秘,它可能会教会我很多东西来完全理解这个问题。

这里的代码:

class MainFrame(wx.Frame):

    TITLE = "Frame"
    POSITION = wx.DefaultPosition
    SIZE = wx.DefaultSize
    STYLE = wx.DEFAULT_FRAME_STYLE
    LAYOUT_MANAGER = wx.GridBagSizer()

    def __init__(
            self,
            parent = None,
            id = wx.ID_ANY,
            title = TITLE,
            pos = POSITION,
            size = SIZE,
            style = STYLE,
            name = wx.FrameNameStr
            ):
        super(MainFrame, self).__init__(parent, id, title, pos, size, style,
                                        name)
        self.SetSizerAndFit(self.LAYOUT_MANAGER)
        self.panel = MainPanel(parent=self)

NameError: global name 'LAYOUT_MANAGER' is not defined我的问题很简单:如果我按如下方式引用 LAYOUT_MANAGER为什么会得到:

self.SetSizerAndFit(LAYOUT_MANAGER)

删除self引用,即。

为什么我很困惑?仅仅因为在此方法中,对 , 等字段的引用POSITION没有SIZE任何前缀self,但如果我使用字段 LAYOUT_MANAGER 作为方法的参数,则需要引用SetSizerAndFit...

是什么赋予了?!

我可能忘记了这里语言最自然的范围/可见性规则..但鉴于我知道的很少,能够写size = SIZE(没有self.)但不能写只是没有意义LAYOUT_MANAGER,并且要求self.LAYOUT_MANAGER? !

4

2 回答 2

4

你说:

仅仅因为在此方法中,对诸如 POSITION、SIZE 等字段的引用没有任何前缀 self,但如果我使用字段 LAYOUT_MANAGER 作为方法 SetSizerAndFit 的参数,则需要引用...

Technically, no. The references to POSITION, SIZE, etc. are not made inside the method, they are made in the def line. The def line itself has access to the enclosing scope, so it can see the variables POSITION and SIZE because they exist in that enclosing scope (which is the class body). However, the actual body of the method does not have access to this scope, so you need to use self.

This difference in scope parallels the difference in when the two are executed. The def statement defines the function, and is executed right when it happens in the source file. The body of the def is not executed until you actually call the function.

于 2013-02-26T19:22:15.263 回答
0

默认参数在声明时在其封闭范围内进行评估,而方法本身在不同的范围内进行评估。

于 2013-02-26T19:23:38.867 回答