wohenhao123 发表于 2023-7-8 16:54:51

59讲作业求助

>>> x = 1
>>> def test():
...   x = 2
...   print(x)
...   class C:
...         x = 3
...         print(x)
...         def m1(self):
...             print(x)
...             print(self.x)
...         def m2(self):
...             x = 4
...             print(x)
...             self.x = 5
...         def m3(self):
...             print(x)
...             print(self.x)
...         c = C()
...         c.m1()
...         c.m2()
...         c.m3()
但是跑出来会报错,
test()
2
3
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
    test()
File "/Users/shuoyanzhu/Desktop/59讲作业.py", line 17, in test
    class C:
File "/Users/shuoyanzhu/Desktop/59讲作业.py", line 30, in C
    c = C()
NameError: cannot access free variable 'C' where it is not associated with a value in enclosing scope
是什么原因?

陶远航 发表于 2023-7-8 16:55:38

根据您提供的代码,有一些缩进和格式问题。我已经为您修复了这些问题,请参考以下代码:

x = 1

def test():
    x = 2
    print(x)
   
    class C:
      x = 3
      print(x)
      
      def m1(self):
            print(x)
            print(self.x)
      
      def m2(self):
            x = 4
            print(x)
            self.x = 5
      
      def m3(self):
            print(x)
            print(self.x)
   
    c = C()
    c.m1()
    c.m2()
    c.m3()

test()


请注意,我将类 C 及其方法的缩进调整为适当的层次,并将 test() 函数调用移至代码末尾。现在您应该可以运行此代码而不会遇到任何错误。当您运行此修复后的代码时,将会得到如下输出:

2
3
2
3
4
1
5


如果您有其他问题,请随时告诉我。
页: [1]
查看完整版本: 59讲作业求助