簡體   English   中英

訪問同一 class 的嵌套 function 中的變量

[英]Accessing a variable within a nested function of the same class

我正在嘗試訪問function_3中的variable - 我應該如何 go 這樣做?

class A:
    def function_1(self):
        
        def function_2(self):
            self.variable = 'Hello'
        function_2(self)
    
    function_1(self)

    def function_3(self):
        print(self.variable)
    
    function_3(self)

名稱self來自這里def function_2(self):陰影名稱self來自這里def function_1(self):

class A:
    def function_1(self):
        def function_2(self): # Here name `self` shadows name `self` from previous line
            self.variable = 'Hello'

        function_2(self)

    function_1(self) # Here you have no `self` variable

    def function_3(self):
        print(self.variable)

    function_3(self) # Here you have no `self` variable too

我想你想實現這種行為

class A:
    def function_1(self):
        def function_2(x):
            x.variable = 'Hello'

        function_2(self)

    def function_3(self):
        print(self.variable)


a = A()
a.function_1()
a.function_3()
> Hello

如果我誤解了您想要做什么,請大聲喊叫,但看起來您需要使用 A() 創建 class A 的實例,然后在該實例上調用 function_1 和 function_3。 請原諒所有的行話,但我希望你能從下面的例子中學習:

class A:
    def function_1(self):
        def function_2(self):
            self.variable = 'Hello'

        function_2(self)


    def function_3(self):
        print(self.variable)



a = A()

a.function_1()
a.function_3()

暫無
暫無

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

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