python 从外部范围隐藏名称
时间: 2023-03-26 08:01:38 浏览: 427
Python 可以通过在名称前面添加一个下划线来隐藏名称,例如 _name。这样的名称被视为私有名称,不应该在模块外部使用。此外,还可以使用双下划线来进行名称修饰,例如 __name,这样的名称会被 Python 解释器修改为 _classname__name 的形式,以避免与其他类中的名称冲突。
相关问题
从外部范围隐藏名称 'arr'
要隐藏数组名称 'arr',你可以将其声明为私有变量。在大多数编程语言中,可以使用关键字 'private' 或者在变量名称前面添加下划线 '_' 来声明一个私有变量。这样做可以限制在类或对象之外访问该变量,从而保护数据的安全性。例如,在Python中,你可以这样声明一个私有数组:
```python
class MyClass:
def __init__(self):
self._arr = [1, 2, 3] # 使用下划线来隐藏变量名称
def get_arr(self):
return self._arr
obj = MyClass()
print(obj.get_arr()) # [1, 2, 3]
print(obj._arr) # AttributeError: 'MyClass' object has no attribute '_arr'
```
在上面的示例中,使用了下划线来隐藏数组名称 'arr',并且只允许通过公共方法 'get_arr' 访问它。在对象外部使用 '_arr' 会导致 'AttributeError' 异常。
从外部范围隐藏名称 'timex'
要隐藏名称"timex",您可以使用Python中的下划线(underscore)来表示私有变量。这样,其他人就不会直接访问它,而是通过公共方法来访问。
例如,将名称“timex”更改为“_timex”,并创建一个公共方法来访问它:
```python
class MyClass:
def __init__(self, timex):
self._timex = timex
def get_timex(self):
return self._timex
```
现在,您可以使用该方法来访问“timex”,但不能直接访问它:
```python
obj = MyClass("2021-07-01")
print(obj.get_timex()) # Output: 2021-07-01
print(obj._timex) # This will raise a warning or error
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)