#global variable
_test__x=13
class test:
def __init__(self,x):
self.__x=x
def rex(self):
return __x
d = test(5)
print(d.rex())
Run Code Online (Sandbox Code Playgroud)
如果我运行此代码,它将返回 13 我知道解释器应用了名称修饰,因此变量__x变成了_test__x
但这与全局变量相同。
我尝试使用,self._test__x但没有用
如何访问__x声明的变量__init __.py而不是全局变量?
根据文档,名称修改发生在类主体中的任何位置:
当在类定义中文本出现的标识符以两个或多个下划线字符开头并且不以两个或多个下划线结尾时,它被视为该类的私有名称...此转换独立于其中的语法上下文。使用标识符。
本教程示例显示,类内的属性也发生了损坏。
但真正的问题是您的代码混淆了名称空间。您最初展示的构造函数
def __init__(self, x):
__x = x
Run Code Online (Sandbox Code Playgroud)
创建一个局部变量_test__x,该变量在完成后立即被丢弃。
要正确分配实例属性:
def __init__(self, x):
self.__x = x
Run Code Online (Sandbox Code Playgroud)
这将创建一个名称实际上为 的属性_test__x。
如果你真的想分配全局:
def __init__(self, x):
global __x
__x = x
Run Code Online (Sandbox Code Playgroud)
或者
def __init__(self, x):
global _test__x
__x = x
Run Code Online (Sandbox Code Playgroud)
getter 需要访问实例属性,就像构造函数需要设置它一样。当前版本正在访问全局,因为_tesy__x本地名称空间中不存在该名称:
def rex(self):
return __x
Run Code Online (Sandbox Code Playgroud)
要返回属性,请添加命名空间:
def rex(self):
return self.__x
Run Code Online (Sandbox Code Playgroud)
话虽这么说,如果您有一个带有前导双下划线的模块级属性(您不应该这样做),那么您将很难在类中访问它。你必须经历globals这样的事情:
globals()['__x']
Run Code Online (Sandbox Code Playgroud)
我很久以前就提出过这个问题的无耻插件:How to access private variable of Python module from class。
另一个有趣的事实:如果你的类名全部是下划线,则根本不会发生名称修改。_您可以通过命名类、__、___、____等来避免所有问题。
| 归档时间: |
|
| 查看次数: |
230 次 |
| 最近记录: |