在项目中见到__all__的使用,故此记录
作用:
python模块中的__all__,用于模块导入时限制,如:from module import *
此时被导入模块若定义了__all__属性,则只有__all__内指定的属性、方法、类可被导入;若没定义,则导入模块内的所有公有属性,方法和类。
项目代码:
import redis
class Client(object):
def __init__(self, **kwargs):
self.connection_settings = kwargs or {'host': 'localhost', 'port': 6379, 'db': 0}
def redis(self):
return redis.Redis(**self.connection_settings)
def update(self, d):
self.connection_settings.update(d)
def connection_setup(**kwargs):
global connection, client
if client:
client.update(kwargs)
else:
client = Client(**kwargs)
connection = client.redis()
def get_client():
global connection
return connection
client = Client()
connection = client.redis()
__all__ = ['connection_setup', 'get_client']
__all__ 的限制后,外部使用import *导入的时候,只有‘connection_setup', 'get_client' 方法可以被引用,