为什么方法无法访问类变量?

2024-05-10

我试图理解Python中的变量作用域,除了我不明白为什么类变量不能从其方法访问的部分之外,大多数事情对我来说都很清楚。
在下面的例子中mydef1()无法访问a,但如果a可以在全局范围(类定义之外)声明。

class MyClass1:
    a = 25
    def mydef1(self):
        print(a)
ins1 = MyClass1()
ins1.mydef1()

Output

Traceback (most recent call last):
  File "E:\dev\Python\scope_test2.py", line 6, in <module>
    ins1.mydef1()
  File "E:\dev\Python\scope_test2.py", line 4, in mydef1
    print(a)
NameError: name 'a' is not defined

重要的是要了解其中一些评论并不等同。MyClass.a是班级本身的成员,self.a是类实例的成员。

当你使用self.a它会返回a从课堂上,因为没有a在实例上。如果还有一个a如果它是实例的成员,它将返回它。通常,实例 a 是使用以下设置的__init__构造函数。这两者可以同时存在。

class MyClass1:
    a = 25

    def __init__(self):
        self.a = 100

    def instance_a(self):
        print(self.a)

    def change_instance_a(self):
        self.a = 5

    def class_a(self):
        print(MyClass1.a)

    def change_class_a(self):
        MyClass1.a = 10


# Create two instances
ins1 = MyClass1()
ins2 = MyClass1()

# Both instances have the same Class member a, and the same instance member a
ins1.instance_a()
ins2.instance_a()
ins1.class_a()
ins2.class_a()

# Now lets change instance a on one of our instances
ins1.change_instance_a()

# Print again, see that class a values remain the same, but instance a has
# changed on one instance only
print()
ins1.instance_a()
ins2.instance_a()
ins1.class_a()
ins2.class_a()

# Lets change the class member a on just one instance
ins1.change_class_a()

# Both instances now report that new value for the class member a
print()
ins1.instance_a()
ins2.instance_a()
ins1.class_a()
ins2.class_a()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么方法无法访问类变量? 的相关文章

随机推荐