为什么set_a不能访问MyClass实例的属性,但set_b可以?
NameError: global name 'my_instance' is not defined
代码:
#!/usr/bin/env python
class MyClass(object):
a = 1
b = 2
def set_a():
my_instance.a = 5
my_instance.b = 6
def main():
def set_b():
my_instance.a = 3
my_instance.b = 4
my_instance = MyClass()
print my_instance.a, my_instance.b
set_b()
print my_instance.a, my_instance.b
set_a()
print my_instance.a, my_instance.b
if __name__ == "__main__":
main()
答案 0 :(得分:1)
将您的实例作为参数传递:
def set_a(my_a):
my_a.a = 5
my_a.b = 6
def main():
def set_b(my_a):
my_a.a = 3
my_a.b = 4
my_instance = MyClass()
print my_instance.a, my_instance.b
set_b(my_instance)
print my_instance.a, my_instance.b
set_a(my_instance)
print my_instance.a, my_instance.b
if __name__ == "__main__":
main()
答案 1 :(得分:0)
函数set_a
没有看到my_instance
,因为它是在不同的范围内定义的。如果它将在main之外定义,那么它应该工作:
my_instance = None
...
def set_a(): ...
...
def main(): ...
虽然我建议将my_instance
作为参数传递而不是定义为全局变量。