如何用Python实现单例模式的五种不同方法?

2026-05-16 22:551阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1073个文字,预计阅读时间需要5分钟。

如何用Python实现单例模式的五种不同方法?

一、classmethod装饰器简介

classmethod装饰器用于装饰类方法,使得该方法可以直接通过类来调用,而不仅仅局限于实例。通过使用classmethod装饰器,可以在不创建类实例的情况下访问类方法。

二、使用classmethod装饰器

以下是一个使用classmethod装饰器的示例:

pythonclass MyClass: @classmethod def my_class_method(cls): print(这是一个类方法,可以通过类名直接调用。)

通过类名调用类方法MyClass.my_class_method()

输出结果:

如何用Python实现单例模式的五种不同方法?

这是一个类方法,可以通过类名直接调用。

三、classmethod装饰器的作用

1. 提供了一种在类级别上定义方法的方式,使得类方法可以在不创建实例的情况下直接通过类名调用。

2.有助于将类方法和实例方法区分开来,提高代码的可读性和可维护性。

3.可以在类方法中直接访问类的属性和方法,而不需要通过实例来访问。

总结:

classmethod装饰器是Python中一种非常有用的装饰器,它可以让我们在类级别上定义方法,使得类方法可以直接通过类名调用。通过使用classmethod装饰器,可以提高代码的可读性和可维护性。

一、classmethod装饰器

# 全局变量 ip = '192.168.13.98' port = '3306' class MySQL: __instance = None def __init__(self, ip, port): self.ip = ip self.port = port @classmethod def instance(cls, *args, **kwargs): if args or kwargs: cls.__instance = cls(*args, **kwargs) return cls.__instance obj1 = MySQL.instance(ip, port) obj2 = MySQL.instance() obj3 = MySQL.instance() print(obj1) print(obj2, obj2.__dict__) print(obj3, obj3.__dict__)

输出结果

<main.MySQL object at 0x058D6F30>
<main.MySQL object at 0x058D6F30> {'ip': '192.168.13.98', 'port': '3306'}
<main.MySQL object at 0x058D6F30> {'ip': '192.168.13.98', 'port': '3306'}

二、类的装饰器

def singlegon(cls): _instance = cls(ip, port) def wrapper(*args, **kwargs): if args or kwargs: return cls(*args, **kwargs) return _instance return wrapper @singlegon class MySQL1: def __init__(self, ip, port): self.ip = ip self.port = port obj1 = MySQL1() obj2 = MySQL1() obj3 = MySQL1('1.1.1.3', 8080) print(obj1) print(obj2, obj2.__dict__) print(obj3, obj3.__dict__)   

运行结果

<main.MySQL1 object at 0x04C102B0>
<main.MySQL1 object at 0x04C102B0> {'ip': '192.168.13.98', 'port': '3306'}
<main.MySQL1 object at 0x04C10310> {'ip': '1.1.1.3', 'port': 8080}

三、元类

class Mymetaclass(type): def __init__(self, class_name, class_bases, class_dic): super().__init__(class_name, class_bases, class_dic) self.__instance = self(ip, port) def __call__(self, *args, **kwargs): if args or kwargs: obj = self.__new__(self) self.__init__(obj, *args, **kwargs) self.__instance = obj return self.__instance class MySQL2(metaclass=Mymetaclass): def __init__(self, ip, port): self.ip = ip self.port = port obj1 = MySQL2() obj2 = MySQL2() obj3 = MySQL2('1.1.1.3', 80) print(obj1) print(obj2, obj2.__dict__) print(obj3, obj3.__dict__)

运行结果

<main.MySQL2 object at 0x04D003B0>
<main.MySQL2 object at 0x04D003B0> {'ip': '192.168.13.98', 'port': '3306'}
<main.MySQL2 object at 0x04D003D0> {'ip': '1.1.1.3', 'port': 80}

四、模块导入

# instance.py class MySQL: def __init__(self, ip, port): self.ip = ip self.port = port ip = '192.168.13.98' port = 3306 instance = MySQL(ip, port) # 测试代码 import os, sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) from test import instance obj1 = instance.instance obj2 = instance.instance obj3 = instance.MySQL('1.1.1.3', 80) print(obj1) print(obj2, obj2.__dict__) print(obj3, obj3.__dict__)

运行结果

<day30.instance.MySQL object at 0x052B0AB0>
<day30.instance.MySQL object at 0x052B0AB0> {'ip': '192.168.13.98', 'port': 3306}
<day30.instance.MySQL object at 0x052B03F0> {'ip': '1.1.1.3', 'port': 80}

五、重写__new__()

class MySQL3(object): __instance = None __first_init = True def __init__(self, ip, port): if self.__first_init: self.ip = ip self.port = port self.__first_init = False def __new__(cls, *args, **kwargs): if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance obj1 = MySQL3(ip, port) obj2 = MySQL3(ip, port) obj3 = MySQL3('1.1.1.3', 80) print(obj1) print(obj2, obj2.__dict__) print(obj3, obj3.__dict__)

运行结果

<main.MySQL3 object at 0x059603F0>
<main.MySQL3 object at 0x059603F0> {'ip': '192.168.13.98', 'port': '3306', '_MySQL3__first_init': False}
<main.MySQL3 object at 0x059603F0> {'ip': '192.168.13.98', 'port': '3306', '_MySQL3__first_init': False}

注:前四种可以实现单例模式,但都不是绝对单例模式,可以创建新的对象,但是第五种方式是绝对单例模式,全局只能真正创建一次对象

以上就是python 实现单例模式的5种方法的详细内容,更多关于python 单例模式的资料请关注易盾网络其它相关文章!

标签:5种方法

本文共计1073个文字,预计阅读时间需要5分钟。

如何用Python实现单例模式的五种不同方法?

一、classmethod装饰器简介

classmethod装饰器用于装饰类方法,使得该方法可以直接通过类来调用,而不仅仅局限于实例。通过使用classmethod装饰器,可以在不创建类实例的情况下访问类方法。

二、使用classmethod装饰器

以下是一个使用classmethod装饰器的示例:

pythonclass MyClass: @classmethod def my_class_method(cls): print(这是一个类方法,可以通过类名直接调用。)

通过类名调用类方法MyClass.my_class_method()

输出结果:

如何用Python实现单例模式的五种不同方法?

这是一个类方法,可以通过类名直接调用。

三、classmethod装饰器的作用

1. 提供了一种在类级别上定义方法的方式,使得类方法可以在不创建实例的情况下直接通过类名调用。

2.有助于将类方法和实例方法区分开来,提高代码的可读性和可维护性。

3.可以在类方法中直接访问类的属性和方法,而不需要通过实例来访问。

总结:

classmethod装饰器是Python中一种非常有用的装饰器,它可以让我们在类级别上定义方法,使得类方法可以直接通过类名调用。通过使用classmethod装饰器,可以提高代码的可读性和可维护性。

一、classmethod装饰器

# 全局变量 ip = '192.168.13.98' port = '3306' class MySQL: __instance = None def __init__(self, ip, port): self.ip = ip self.port = port @classmethod def instance(cls, *args, **kwargs): if args or kwargs: cls.__instance = cls(*args, **kwargs) return cls.__instance obj1 = MySQL.instance(ip, port) obj2 = MySQL.instance() obj3 = MySQL.instance() print(obj1) print(obj2, obj2.__dict__) print(obj3, obj3.__dict__)

输出结果

<main.MySQL object at 0x058D6F30>
<main.MySQL object at 0x058D6F30> {'ip': '192.168.13.98', 'port': '3306'}
<main.MySQL object at 0x058D6F30> {'ip': '192.168.13.98', 'port': '3306'}

二、类的装饰器

def singlegon(cls): _instance = cls(ip, port) def wrapper(*args, **kwargs): if args or kwargs: return cls(*args, **kwargs) return _instance return wrapper @singlegon class MySQL1: def __init__(self, ip, port): self.ip = ip self.port = port obj1 = MySQL1() obj2 = MySQL1() obj3 = MySQL1('1.1.1.3', 8080) print(obj1) print(obj2, obj2.__dict__) print(obj3, obj3.__dict__)   

运行结果

<main.MySQL1 object at 0x04C102B0>
<main.MySQL1 object at 0x04C102B0> {'ip': '192.168.13.98', 'port': '3306'}
<main.MySQL1 object at 0x04C10310> {'ip': '1.1.1.3', 'port': 8080}

三、元类

class Mymetaclass(type): def __init__(self, class_name, class_bases, class_dic): super().__init__(class_name, class_bases, class_dic) self.__instance = self(ip, port) def __call__(self, *args, **kwargs): if args or kwargs: obj = self.__new__(self) self.__init__(obj, *args, **kwargs) self.__instance = obj return self.__instance class MySQL2(metaclass=Mymetaclass): def __init__(self, ip, port): self.ip = ip self.port = port obj1 = MySQL2() obj2 = MySQL2() obj3 = MySQL2('1.1.1.3', 80) print(obj1) print(obj2, obj2.__dict__) print(obj3, obj3.__dict__)

运行结果

<main.MySQL2 object at 0x04D003B0>
<main.MySQL2 object at 0x04D003B0> {'ip': '192.168.13.98', 'port': '3306'}
<main.MySQL2 object at 0x04D003D0> {'ip': '1.1.1.3', 'port': 80}

四、模块导入

# instance.py class MySQL: def __init__(self, ip, port): self.ip = ip self.port = port ip = '192.168.13.98' port = 3306 instance = MySQL(ip, port) # 测试代码 import os, sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) from test import instance obj1 = instance.instance obj2 = instance.instance obj3 = instance.MySQL('1.1.1.3', 80) print(obj1) print(obj2, obj2.__dict__) print(obj3, obj3.__dict__)

运行结果

<day30.instance.MySQL object at 0x052B0AB0>
<day30.instance.MySQL object at 0x052B0AB0> {'ip': '192.168.13.98', 'port': 3306}
<day30.instance.MySQL object at 0x052B03F0> {'ip': '1.1.1.3', 'port': 80}

五、重写__new__()

class MySQL3(object): __instance = None __first_init = True def __init__(self, ip, port): if self.__first_init: self.ip = ip self.port = port self.__first_init = False def __new__(cls, *args, **kwargs): if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance obj1 = MySQL3(ip, port) obj2 = MySQL3(ip, port) obj3 = MySQL3('1.1.1.3', 80) print(obj1) print(obj2, obj2.__dict__) print(obj3, obj3.__dict__)

运行结果

<main.MySQL3 object at 0x059603F0>
<main.MySQL3 object at 0x059603F0> {'ip': '192.168.13.98', 'port': '3306', '_MySQL3__first_init': False}
<main.MySQL3 object at 0x059603F0> {'ip': '192.168.13.98', 'port': '3306', '_MySQL3__first_init': False}

注:前四种可以实现单例模式,但都不是绝对单例模式,可以创建新的对象,但是第五种方式是绝对单例模式,全局只能真正创建一次对象

以上就是python 实现单例模式的5种方法的详细内容,更多关于python 单例模式的资料请关注易盾网络其它相关文章!

标签:5种方法