簡體   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