簡體   English   中英

在類內部使用閉包(“ python 2.7”)“實例無屬性”

[英]“Instance has no attribute” using closure inside class (python 2.7)

我的問題是關於具有以下結構的代碼:

class MainClass():
    def __init__(self):
        self.Func1()
        #some code

    def Func1(self):
        def Func2(self):
            print "test"
            #some more code

        def Func3(self):
            self.Func2()
            #some more code

        self.Func3()

MainClass()

當我使用這種結構運行某些東西時,python給出錯誤:“ MainClass實例沒有屬性'Func3'”。 我不確定我是否誤解了我對閉包的理解,還是在函數內部使用閉包時犯了一個錯誤。

在此先感謝您的任何回答,危害

如您的帖子中所定義, Func2Func3不屬於MainClass類。

您定義的函數只能在Func1內部看到,那么self參數不是對象的當前實例,可以像這樣重寫

def Func1(self):
    def Func2():
        print "test"
        #some more code

    def Func3():
        Func2()
        #some more code

   Func3()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM