zoukankan      html  css  js  c++  java
  • python脚本中__all__变量的用法

    Python中一个py文件就是一个模块,“__all__”变量是一个特殊的变量,可以在py文件中,也可以在包的__init__.py中出现。

    1、在普通模块中使用时,表示一个模块中允许哪些属性可以被导入到别的模块中,

         如:全局变量,函数,类。如下,test1.py和main.py

         test1.py

    1
    2
    3
    4
    5
    6
    7
    __all__=["test"]
     
    def test():
        print('----test-----')
          
    def test1():
        print('----test1----')

     
       main.py

    1
    2
    3
    4
    5
    6
    7
    8
    from test1 import *
          
    def main():
        test()
          
        #test1()
          
    main()

     
    两个文件在同一个目录下。

    此时执行python main.py时结果如下:


    但是如果放开main.py的注释后,如下:


    那么在模块中的__all__变量就是为了限制或者指定能被导入到别的模块的函数,类,全局变量等,如果指定了那么只能是指定的那些可以被导入,没有指定默认就是全部可以导入,当然私有属性应该除外。

    2、在包下的__init__.py中

    sound/effects/__init__.py中添加__all__ = ["echo", "surround", "reverse"]

    那么就会在from sound.effects import *时,包含上面三个模块。当__init__.py为空时,只是导入这个包,并非导入模块。

    __init__.py中可以执行一些初始化内容,比如:

    from . import test1 导入当前目录下的test1模块

    from .. import test 导入上一层目录下的test模块

    因为导入 包时会首先执行下__init__.py这个文件

    原文:https://blog.csdn.net/chuan_day/article/details/79694319 

  • 相关阅读:
    【spring】【转】Spring 框架的设计理念与设计模式分析
    【ML】贝叶斯估计
    【weka】Use weka in your java code
    【spring】spring的一些思想,哪些bean需要注入
    20130320
    【转】中文分词技术(中文分词原理)
    【ML】【GM】【转】图模型(graphical model, GM)的表示
    【hibernate】【转】Hibernate的一些使用技巧
    20130326
    【orange】【转】orange使用
  • 原文地址:https://www.cnblogs.com/wisir/p/12526401.html
Copyright © 2011-2022 走看看