|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
>>> 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
是什么原因?
根据您提供的代码,有一些缩进和格式问题。我已经为您修复了这些问题,请参考以下代码:
- 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() 函数调用移至代码末尾。现在您应该可以运行此代码而不会遇到任何错误。当您运行此修复后的代码时,将会得到如下输出:
如果您有其他问题,请随时告诉我。
|
|