如何调用内部方法

2024-10-03 23:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我试图理解全局变量和局部变量之间的差异。在运行时生成以下错误:#

File "m:\python lessons\globalAndLocal_1.py", line 21, in globalVsLocal_1
    self.g2()
NameError: name 'self' is not defined

注意

 i want to call g2 from within g1

请告诉我如何调用方法g2()

代码

class globalVsLocal_1:

    def f1(self):
        global a #this is to reference a variable declared in the global context.
        print ("f1 a = %s"%(a)) # if global a was not declared in the first line, generates this line an error as variable a not defined is
        a = a + 10            
        print ("f1 a = %s"%(a))

    def f2(self):
        print("f2 a = %s"%(a))

    def f3(self):
        print("f3 b = %s"%(b))
        #b = b + 1   #activating this line will yield an error. Because the absence of the keyword global. the print statement works immaculately without global keyword because it just reads the value without 
                        #manipulate it
        print("f3 b = %s"%(b))

    def g1(self):
        def g2():
                print("g2 b = %s "%(b))
    g2()

a = 1
b = 20
obj = globalVsLocal_1()
obj.f1()
obj.f2()
obj.f3()
obj.g1()

Tags: theinselfobjisdeflinenot
2条回答

g2()的作用域是函数g1()的局部作用域,因此不能在外部调用它。在类定义的中间尝试调用g2()也是不寻常的。

class ...
   def g1(self):
     def g2():
        print("g2 b = %s "%(b))

     g2()
class globalVsLocal_1:

    def f1(self):
        global a #this is to reference a variable declared in the global context.
        print ("f1 a = %s"%(a)) # if global a was not declared in the first line, generates this line an error as variable a not defined is
        a = a + 10            
        print ("f1 a = %s"%(a))

    def f2(self):
        print("f2 a = %s"%(a))

    def f3(self):
        print("f3 b = %s"%(b))
        #b = b + 1   #activating this line will yield an error. Because the absence of the keyword global. the print statement works immaculately without global keyword because it just reads the value without 
        #manipulate it
        print("f3 b = %s"%(b))

    def g1(self):
        def g2():
            print("g2 b = %s "%(b))
        g2()

a = 1
b = 20
obj = globalVsLocal_1()
obj.f1()
obj.f2()
obj.f3()
obj.g1()

调用g2时缺少缩进。 这将提供以下输出

f1 a = 1
f1 a = 11
f2 a = 11
f3 b = 20
f3 b = 20
g2 b = 20 

相关问题 更多 >