国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python中模塊的__all__屬性詳解

2020-02-16 10:30:28
字體:
來源:轉載
供稿:網友

python模塊中的__all__屬性,可用于模塊導入時限制,如:

from module import *

此時被導入模塊若定義了__all__屬性,則只有__all__內指定的屬性、方法、類可被導入。

若沒定義,則導入模塊內的所有公有屬性,方法和類

# kk.py class A():   def __init__(self,name,age):     self.name=name     self.age=age class B():   def __init__(self,name,id):     self.name=name     self.id=id def func():   print 'func() is called!' def func1():   print 'func1() is called!' 
#test_kk.py from kk import * #由于kk.py中沒有定義__all__屬性,所以導入了kk.py中所有的公有屬性、方法、類 a=A('python','24') print a.name,a.age b=B('python',123456) print b.name,b.id func() func1() 

運行結果:

python 24
python 123456
func() is called!
func1() is called!

#kk.py __all__=('A','func') #在別的模塊中,導入該模塊時,只能導入__all__中的變量,方法和類 class A():   def __init__(self,name,age):     self.name=name     self.age=age class B():   def __init__(self,name,id):     self.name=name     self.id=id def func():   print 'func() is called!' def func1():   print 'func1() is called!' 
#test_kk.py from kk import * #kk.py中定義了__all__屬性,只能導入__all__中定義的屬性,方法和類 a=A('python','24') print a.name,a.age func() #func1() #NameError: name 'func1' is not defined #b=B('python',123456) #NameError: name 'B' is not defined 

運行結果:

python 24
func() is called!

#kk.py def func(): #模塊中的public方法   print 'func() is called!' def _func(): #模塊中的protected方法   print '_func() is called!' def __func():#模塊中的private方法   print '__func() is called!' 
#test_kk.py from kk import * #這種方式只能導入公有的屬性,方法或類【無法導入以單下劃線開頭(protected)或以雙下劃線開頭(private)的屬性,方法或類】  func() #_func() #NameError: name '_func' is not defined #__func() #NameError: name '__func' is not defined 

運行結果:

func() is called!

__all__=('func','__func','_A') #放入__all__中所有屬性均可導入,即使是以下劃線開頭 class _A():   def __init__(self,name):     self.name=name def func():    print 'func() is called!'  def func1():    print 'func1() is called!'  def _func():    print '_func() is called!'  def __func():    print '__func() is called!'  
from kk import *   func()  #func1() #func1不在__all__中,無法導入 NameError: name 'func1' is not defined #_func() #_func不在__all__中,無法導入 NameError: name '_func' is not defined __func() #__func在__all__中,可以導入 a=_A('python') #_A在__all__中,可以導入 print a.name             
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 和田市| 洪湖市| 宁明县| 都安| 成武县| 奉化市| 台江县| 喀什市| 明光市| 淮滨县| 衡山县| 明水县| 斗六市| 长葛市| 阳西县| 若羌县| 宝坻区| 图片| 陆河县| 鄄城县| 中卫市| 孝感市| 阿图什市| 龙海市| 漠河县| 贞丰县| 喀喇沁旗| 江川县| 磐石市| 贵溪市| 平邑县| 吴忠市| 纳雍县| 莆田市| 汝城县| 治多县| 鄄城县| 临桂县| 青岛市| 得荣县| 平谷区|