Loading

Python - 单例模式

about

所谓单例,是指一个类的实例从始至终只能被创建一次,并且对外部提供一个访问它的全局访问点。
优点

  • 对唯一实例的受控访问。
  • 单例相当于全局变量,但不会给命名空间造成污染。

在Python中,实现单例模式的方式有多种。

基于__new__实现

class Singleton(object):

	def __new__(cls, *args, **kwargs):
		if not hasattr(cls, '_instance'):
			cls._instance = super(Singleton, cls).__new__(cls)
		return cls._instance 
	
	def __init__(self, num):
		self.num = num

num1 = Singleton(10)
num2 = Singleton(20)
print(num1.num, num2.num)  # 20 20
print(id(num1), id(num2))  # 2467135043848 2467135043848

示例:

import logging


class LoggerHandler:

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(LoggerHandler, cls).__new__(cls)
        return cls._instance

    def __init__(self, log_name, log_level, file_path, stream_level='info', file_level='warning'):
        self.logger_name = log_name
        self.logger_level = log_level
        self.file_path = file_path
        self.stream_level = stream_level
        self.file_level = file_level

        # 创建日志对象
        self.logger = logging.getLogger(self.logger_name)
        # 设置默认日志级别
        self.logger.setLevel(self.logger_level)
        # 设置日志输出流
        to_stream = logging.StreamHandler()
        to_file = logging.FileHandler(self.file_path)
        # 设置日志输出级别
        to_stream.setLevel(self.stream_level)
        to_file.setLevel(self.file_level)
        # 设置日志输出格式
        formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")
        to_stream.setFormatter(formatter)
        to_file.setFormatter(formatter)
        self.logger.addHandler(to_stream)
        self.logger.addHandler(to_file)


log = LoggerHandler(
    log_name='log',
    log_level=logging.INFO,
    file_path='./log.log',
    stream_level=logging.INFO,
    file_level=logging.WARNING
)

log.logger.info('info')
log.logger.error('error')
log.logger.warning('warning')

欢迎斧正,that's all see also:
posted @ 2019-11-25 18:20  听雨危楼  阅读(148)  评论(0编辑  收藏  举报