繁体   English   中英

在python3中的函数内部定义函数

[英]defining a function inside a function in python3

我正在尝试在python3的函数内定义一个函数

from gi.repository import Gtk, GObject

class EntryWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Generate Init")
        self.set_size_request(100, 50)
        self.nument = Gtk.Entry()

        <did some work>

    def get_nument(self,nument):
      numele= self.nument.get_text()
      print(numele)
      <did some more work and define a function again>
        def get_specs(self,spec):
            numspec=self.spec.get_text()

导致错误:

Traceback (most recent call last):
  File "hw3.py", line 42, in get_nument
    self.spec.connect("activate",self.get_specs)
AttributeError: 'EntryWindow' object has no attribute 'get_specs'

我真的是python的新手,所以努力尝试理解self的范围和此错误的来源。 另外,根据这篇文章 ,通过在函数内部声明一个函数,我做的事情可能真的很有趣。

我需要定义一个函数( get_specs ),该函数将由另一个函数( get_nument )调用。

这实际上是一个gtk3代码,但我猜它是python的问题。 完整的代码,目前状态可以在这里看到。 请帮助。

这个:

File "hw3.py", line 42, in get_nument
  self.spec.connect("activate",self.get_specs)

get_nument ,将get_specs引用为get_specs 因此,请尝试:

self.spec.connect("activate", get_specs)

它只是您在get_nument范围内声明的get_nument ,因此它与任何变量一样。 一个例子:

def foo(self):

    x = 34
    def bar():
        # ...

    # Use x:
    print(x)
    # Use bar:
    print(bar())  # Note: no self, because bar isn't part of self.

暂无
暂无

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

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