带双下划线的变量不能在类中使用?

2024-03-28 10:52:04 发布

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

考虑以下代码:

def __g_fun():
    pass

__a = 3
a=3

class Test(object):
    def __init__(self):
        global a,__a
        print "locals:",locals()
        print "global:",globals()
        self.aa = __a
    def fun(self):
        return __g_fun()


t=Test()
t.fun()

输出:

locals: {'self': <__main__.Test object at 0x7f53580d50d0>}

global: {'__g_fun': <function __g_fun at 0x7f53580c52a8>, 'a': 3, '__a': 3, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'test.py', '__package__': None, 'Test': <class '__main__.Test'>, '__name__': '__main__', '__doc__': None}

Traceback (most recent call last):
  File "test.py", line 19, in <module>
    t=Test()
  File "test.py", line 11, in __init__
    self.aa = __a
NameError: global name '_Test__a' is not defined

是不是带双下划线的变量不能在类中使用?你知道吗


Tags: inpytestselfobjectinitmaindef
1条回答
网友
1楼 · 发布于 2024-03-28 10:52:04

实际上,Python编译器以一种特殊的方式处理类代码中的双下划线前缀- 在编译时,这些变量会被名称损坏,以包含类名作为前缀- 这样类Test中任何地方的名称__a都将更改为_Test__a。(请记住,“编译时”通常对用户是透明的,可以被视为“在程序运行时”)

这是一个特性,它允许一个人拥有在类的方法中评估的名称,而不是由它的子类(不是以自动形式)评估的名称——在某些其他语言中,这个特性是由“私有”成员修饰符执行的。你知道吗

查看Python类文档:https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references

相关问题 更多 >