python模块中的__all__属性

本文详细介绍了Python中__all__属性的作用及用法,包括如何限制模块导入时的内容,以及如何通过__all__属性导入受保护和私有的方法、类等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://blog.youkuaiyun.com/sxingming/article/details/52903377

python模块中的__all__属性,可用于模块导入时限制,如:
from module import *
此时被导入模块若定义了__all__属性,则只有__all__内指定的属性、方法、类可被导入。

若没定义,则导入模块内的所有公有属性,方法和类 。

 

[python]  view plain  copy
 
  1. # kk.py  
  2. class A():  
  3.     def __init__(self,name,age):  
  4.         self.name=name  
  5.         self.age=age  
  6.   
  7. class B():  
  8.     def __init__(self,name,id):  
  9.         self.name=name  
  10.         self.id=id  
  11.   
  12. def func():  
  13.     print 'func() is called!'  
  14. def func1():  
  15.     print 'func1() is called!'  
[python]  view plain  copy
 
  1. #test_kk.py  
  2. from kk import *  #由于kk.py中没有定义__all__属性,所以导入了kk.py中所有的公有属性、方法、类  
  3. a=A('python','24')  
  4. print a.name,a.age  
  5. b=B('python',123456)  
  6. print b.name,b.id  
  7. func()  
  8. func1()  

运行结果:
python 24
python 123456
func() is called!

func1() is called!

 

[python]  view plain  copy
 
  1. #kk.py  
  2. __all__=('A','func') #在别的模块中,导入该模块时,只能导入__all__中的变量,方法和类  
  3. class A():  
  4.     def __init__(self,name,age):  
  5.         self.name=name  
  6.         self.age=age  
  7.   
  8. class B():  
  9.     def __init__(self,name,id):  
  10.         self.name=name  
  11.         self.id=id  
  12.   
  13. def func():  
  14.     print 'func() is called!'  
  15. def func1():  
  16.     print 'func1() is called!'  
[python]  view plain  copy
 
  1. #test_kk.py  
  2. from kk import *  #kk.py中定义了__all__属性,只能导入__all__中定义的属性,方法和类  
  3. a=A('python','24')  
  4. print a.name,a.age  
  5. func()  
  6. #func1() #NameError: name 'func1' is not defined  
  7. #b=B('python',123456) #NameError: name 'B' is not defined  

 

运行结果:

python 24
func() is called!

[python]  view plain  copy
 
  1. #kk.py  
  2. def func(): #模块中的public方法  
  3.     print 'func() is called!'  
  4.       
  5. def _func(): #模块中的protected方法  
  6.     print '_func() is called!'  
  7.       
  8. def __func():#模块中的private方法  
  9.     print '__func() is called!'  

 

[python]  view plain  copy
 
  1. #test_kk.py  
  2. from kk import *  #这种方式只能导入公有的属性,方法或类【无法导入以单下划线开头(protected)或以双下划线开头(private)的属性,方法或类】    
  3. func()  
  4. #_func() #NameError: name '_func' is not defined  
  5. #__func() #NameError: name '__func' is not defined  

运行结果:
func() is called!

 

[python]  view plain  copy
 
  1. __all__=('func','__func','_A') #放入__all__中所有属性均可导入,即使是以下划线开头  
  2.   
  3. class _A():  
  4.     def __init__(self,name):  
  5.         self.name=name  
  6.   
  7. def func():    
  8.     print 'func() is called!'    
  9.      
  10. def func1():    
  11.     print 'func1() is called!'    
  12.     
  13. def _func():    
  14.     print '_func() is called!'    
  15.         
  16. def __func():    
  17.     print '__func() is called!'   

 

 

[python]  view plain  copy
 
  1. from kk import *      
  2. func()    
  3. #func1() #func1不在__all__中,无法导入 NameError: name 'func1' is not defined  
  4. #_func() #_func不在__all__中,无法导入  NameError: name '_func' is not defined  
  5. __func() #__func在__all__中,可以导入  
  6. a=_A('python') #_A在__all__中,可以导入  
  7. print a.name  

 

运行结果:

func() is called!
__func() is called!
python

 

[python]  view plain  copy
 
  1. #kk.py  
  2. def func():  
  3.     print 'func() is called!'  
  4.       
  5. def _func():  
  6.     print '_func() is called!'  
  7.       
  8. def __func():  
  9.     print '__func() is called!'  
[python]  view plain  copy
 
  1. #test_kk.py  
  2. from kk import func,_func,__func  #可以通过这种方式导入public,protected,private  
  3. func()  
  4. _func() #NameError: name '_func' is not defined  
  5. __func() #NameError: name '__func' is not defined  

运行结果:
func() is called!
_func() is called!
__func() is called!

 

 

[python]  view plain  copy
 
  1. #kk.py  
  2. def func():  
  3.     print 'func() is called!'  
  4.       
  5. def _func():  
  6.     print '_func() is called!'  
  7.       
  8. def __func():  
  9.     print '__func() is called!'  
[python]  view plain  copy
 
  1. #test_kk.py  
  2. import kk  #也可以通过这种方式导入public,protected,private  
  3. kk.func()  
  4. kk._func() #NameError: name '_func' is not defined  
  5. kk.__func() #NameError: name '__func' is not defined  

运行结果:
func() is called!
_func() is called!

__func() is called!

 

[python]  view plain  copy
 
  1. #kk.py  
  2. import sys  
  3.   
  4. __all__ = ["func"]  # 排除了 'sys'  
  5.   
  6. def func():  
  7.     print 'func() is called!'  
[python]  view plain  copy
 
  1. #test_kk.py  
  2. from kk import *  
  3.   
  4. #print sys.path #NameError: name 'sys' is not defined  
  5. func()  

运行结果:
func() is called!
如果一个模块需要暴露的接口改动频繁,__all__ 可以这样定义:
__all__ = [
    "foo",
    "bar",
    "egg",
]
最后多出来的逗号在 Python 中是允许的,也是符合 PEP8 风格的。

 

模块中不使用__all__属性,则导入模块内的所有公有属性,方法和类 。

模块中使用__all__属性,则表示只导入__all__中指定的属性,因此,使用__all__可以隐藏不想被import的默认值。

__all__变量是一个由string元素组成的list变量。
它定义了当我们使用 from <module> import * 导入某个模块的时候能导出的符号(这里代表变量,函数,类等)。
from <module> import * 默认的行为是从给定的命名空间导出所有的符号(当然下划线开头的变量,方法和类除外)。
需要注意的是 __all__ 只影响到了 from <module> import * 这种导入方式,
对于 from <module> import <member> 导入方式并没有影响,仍然可以从外部导入。

 


(完)

转载于:https://www.cnblogs.com/eternal1025/p/8531975.html

<think>好的,用户想了解Python中双下划线(__)的作用和意义。首先,我需要回忆一下相关知识,并结合提供的引用资料来组织回答。 首先,双下划线在Python中主要有几个用途。最常见的是在类中定义特殊方法,比如__init__、__new__,这些方法由解释器自动调用。根据引用[2],__init__其实不是构造方法,真正的构造方法是__new__,这需要解释清楚。另外,双下划线还用于名称修饰(name mangling),在类的属性或方法前加双下划线,Python会对其进行改名,以避免子类与父类的命名冲突。例如,类中的__var会被改成_ClassName__var,这需要举例说明。 然后,可能用户还关心其他情况,比如作为前后双下划线的方法,如__contains__对应in操作符,引用[3]提到x.__contains__(y)等价于y in x,这点可以提及。此外,双下划线有时也用于避免与Python关键字冲突,比如定义class_,但这种情况可能不常见,需要确认是否有必要提到。 还需要注意,双下划线开头和结尾的情况,比如__init__,这是特殊方法,而仅开头双下划线是名称修饰。另外,引用[1]指出单下划线和双下划线有不同的约定,但这里用户只问双下划线,所以重点在双下划线。 然后,根据引用[5],在循环中使用v,_来解包元组,这里的下划线是作为临时变量,但这是单下划线的用法,用户问的是双下划线,所以可能不需要涉及,但需要确认问题是否混淆了单双下划线。不过用户明确问的是双下线,所以这部分可能不相关。 总结需要涵盖以下几点: 1. 特殊方法(如__init__、__new__) 2. 名称修饰(私有变量) 3. 避免命名冲突 4. 其他用法比如魔术方法 需要结构清晰,分点说明,并引用提供的资料。例如,引用[2]说明__init__和__new__的区别,引用[1]提到双下划线的约定和执行层面的意义。 可能还需要举例子,比如名称修饰后的变量名变化,以及如何在子类中访问这些变量。此外,需要指出双下划线不仅是约定,而是由Python解释器强制处理的,这点引用[1]有提到。 最后,生成相关问题,可能涉及单下划线和双下划线的区别,或者特殊方法的应用场景等。</think>### Python中双下划线`__`的作用和意义 #### 1. **特殊方法(魔术方法)** Python中使用双下划线包裹的方法称为“魔术方法”(如`__init__`, `__new__`, `__str__`等),它们由解释器自动调用以实现特定功能。 - `__init__`:常用于对象初始化,但并非构造方法,真正的构造方法是`__new__`[^2]。 - `__contains__`:实现`in`操作符的逻辑,例如`y in x`等价于`x.__contains__(y)`[^3]。 #### 2. **名称修饰(Name Mangling)** 在类的属性或方法名前添加双下划线(如`__var`),Python会对其进行名称修饰,格式为`_ClassName__var`。这种机制主要用于: - **避免子类覆盖父类属性** 例如: ```python class Parent: def __init__(self): self.__value = 10 # 实际存储为 _Parent__value class Child(Parent): def __init__(self): super().__init__() self.__value = 20 # 实际存储为 _Child__value ``` 此时父类和子类的`__value`互不影响。 - **实现伪私有性**(约定上的私有,非强制)[^1]。 #### 3. **避免命名冲突** 双下划线也可用于避免与Python关键字或内置名称冲突,例如: ```python class_ = "ClassName" # 避免使用`class`关键字 ``` #### 4. **其他约定用法** - 双下划线开头和结尾的变量(如`__all__`)通常表示模块级别的公开接口。 - 交互模式中`_`表示上一次计算结果[^4],但这是单下划线的用法,与双下划线无关。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值