python, 在自定义模块中使用公用变量
时间: 2024-03-11 12:51:47 浏览: 34
在自定义模块中使用公用变量,可以将变量定义在模块的顶部,这样其他函数都可以访问该变量。例如:
```python
# module.py
count = 0
def increment():
global count
count += 1
print("count is now:", count)
def decrement():
global count
count -= 1
print("count is now:", count)
```
在上面的例子中,`count` 是一个公用变量,被定义在模块的顶部。`increment()` 和 `decrement()` 函数都可以访问 `count` 变量,并修改它的值。在函数中,需要使用 `global` 关键字来声明变量是全局的,这样才能修改全局变量。
在其他模块中,可以通过 `import` 语句来使用模块中的公用变量和函数:
```python
# main.py
import module
module.increment() # count is now: 1
module.increment() # count is now: 2
module.decrement() # count is now: 1
```
在上面的例子中,`main.py` 文件中通过 `import module` 语句引入了 `module` 模块,然后就可以使用其中的 `increment()` 和 `decrement()` 函数来修改 `count` 变量的值了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)