zoukankan      html  css  js  c++  java
  • Python的程序结构[3] -> 变量/Variable[0] -> 变量类型

    变量类型 / Variable Type


    在 Python 中,变量主要有以下几种,即全局变量,局部变量和内建变量,

    全局变量 / Global Variable


    通常定义于模块内部,大写变量名形式存在,可被其他模块导入,但还有一种特殊的私有变量,以单/双下划线开头,同样定义于模块内,但无法通过 from modelname import * 的方式进行导入。

    局部变量 / Local Variable


    局部变量通常定义于函数内部,变量名以小写形式存在,仅在函数的局部作用域起作用。

    内建变量 / Built-in Variable


    内建变量是一些内置存在的变量,可以通过 vars() 进行查看,常用的有 __name__ 等。

    变量示例 / Variable Example



    下面以一段代码来演示这几种变量之间的区别,

     1 print(vars()) # Show built_in variables
     2 
     3 GLOBAL_VARIABLE = "This is global variable"
     4 _PRIVATE_VARIABLE = "This is private variable"
     5 
     6 def call_local():
     7     local_variable = "This is local variable"
     8     print(local_variable)
     9 
    10 def call_global():
    11     global GLOBAL_VARIABLE
    12     print(GLOBAL_VARIABLE)
    13 
    14 def call_private():
    15     print(_PRIVATE_VARIABLE)
    16 
    17 if __name__ == '__main__':
    18     call_local()
    19     call_global()
    20     call_private()

    上面的代码首先利用 vars() 函数显示了模块中原始存在的内建变量,主要有 __doc__,__name__ 等。随后定义了全局变量 GLOBAL_VARIABLE 和私有的全局变量 _PRIVATE_VARIABLE,call_local 函数中对局部变量进行了调用,在 call_global 函数中,首先通过关键词声明了全局变量,随后对其进行调用,而在 call_private 函数中却没有对私有的全局变量进行 global 声明,但也成功调用了,这便涉及到了 Python 的 LEGB 法则

    {'__doc__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\Users\EKELIKE\Documents\Python Note\3_Program_Structure\3.4_Variable\variable_type.py', '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None}
    This is local variable
    This is global variable
    This is private variable

    最后,我们在另一个模块中尝试导入当前模块的私有全局变量 _PRIVATE_VARIABLE,

     1 from variable_type import *
     2 
     3 print(GLOBAL_VARIABLE)
     4 
     5 try:
     6     print(_PRIVATE_VARIABLE)
     7 except NameError:
     8     print("Name Error, re-import.")
     9     from variable_type import _PRIVATE_VARIABLE
    10     print(_PRIVATE_VARIABLE)

    从输出的结果可以看到,使用 from module import * 的方式是无法将私有的全局变量导入的,但若指明具体的变量名则可以。

    This is global variable
    Name Error, re-import.
    This is private variable

    Note: 此处的全局私有变量使用单下划线和双下划线效果相同。

     相关阅读


    1. LEGB 法则

  • 相关阅读:
    七. 多线程编程3.主线程
    七. 多线程编程1.线程的概念
    六. 异常处理12.断言
    liunx 安装 mysql 5.6
    idea Unable to open debugger port (127.0.0.1:58006) Address already in use: JVM_Bind 的解决办法
    liunx 安装redis 4.0
    liunx 安装jdk1.8
    idea 去除xml文件sql语句背景色
    改变数据库和表编码
    mybatis 按in 函数参数顺序排序
  • 原文地址:https://www.cnblogs.com/stacklike/p/8098924.html
Copyright © 2011-2022 走看看