【问题标题】:defining a function inside a function in python3在python3中的函数内部定义一个函数
【发布时间】:2014-03-23 20:05:28
【问题描述】:

我正在尝试在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真的很陌生,所以努力了解自我的范围和这个错误的起源。另外,根据this post,通过在函数内部声明一个函数,我可能会做一些非常有趣的事情。

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

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

【问题讨论】:

  • 类范围是类范围。功能范围是功能范围。它们是两个不相交的实体。
  • 您能解释一下我如何正确定义它吗?
  • 你想要“正确”是什么意思?
  • 这样从 get_nument 调用函数 get_specs 不会出错
  • 它已经在get_nument() 中。只需像调用范围内的任何其他函数一样调用它。

标签: python function python-3.x


【解决方案1】:

这个:

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 范围内声明的函数,所以它就像任何变量一样。一个例子:

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.

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2014-05-21
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    相关资源
    最近更新 更多