gpt4 book ai didi

Python 私有(private)类变量不是类变量

转载 作者:太空宇宙 更新时间:2023-11-03 19:28:55 24 4
gpt4 key购买 nike

尝试访问__variables时对于类,解析器假定 2 个下划线相对于当前类是私有(private)的。请注意不相关的函数如何获取“私有(private)”变量。

这是一个错误吗?

>>> def f(): pass...>>> class A:...     def g(self):...             f.__x = 1...             def h():...                     pass...             h.__y = 2...             return h...>>> z = A().g()>>> dir(z)['_A__y', '__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']>>> dir(f)['_A__x', '__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

在 python 2.5 和 3.2 上测试

最佳答案

这是一个well documented behavior

This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

关于Python 私有(private)类变量不是类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6967076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com