创建类设计模式-单列模式基于metaclass方法实现.py

"""
metaclass
但是在Python中,class并不只有这一角色。class实际上也是object。当我们使用class定义一个类的时候,Python会执行相应代码并在内存中创建一个名为example的object。
class 类 :自身拥有创建对象(类的实例)的能力。本质还是对象
1、类可以赋值
2、可以拷贝
3、可以增加属性
4、可以作为函数参数传参

# # print a class since it's an object
# >>> print(example)
# <class '__main__.example'>
#
# # assign an attribute to the class
# >>> print(hasattr(example, 'new_attribute'))
# False
# >>> example.new_attribute = 'assign an attribute to the class'
# >>> print(hasattr(example, 'new_attribute'))
# True
# >>> print(example.new_attribute)
# assign an attribute to the class
#
# # assign the class to a variable
# >>> example_mirror = example
# >>> print(example_mirror)
# <class '__main__.example'>
# >>> print(example_mirror())
# <__main__.example object at 0x102e26a90>
#
# # pass class as a parameter
# >>> def echo(cls):
# ... print(cls)
# ...
# >>> echo(example)
# <class '__main__.example'>
#
# """

"""
动态创建class
当我们使用class关键字创建类的时候,Python会自动创建对应的object。像Python中其他大多数情况一样,我们也可以手动创建这个class object。这一操作可以通过type()实现。
>>> print(type(1))
<type 'int'>

>>> print(type('str'))
<type 'str'>

>>> print(type(example()))
<class '__main__.example'>

>>> print(type(example))
<type 'type'>
1、在这里我们看到我们所创建example类的type是'type'。
2、既type的完全不同的功能——type可以动态创建class。
3、type()函数可以接收class的描述来作为参数并返回所生成的class object。type同时具有这两个迥异的功能是由于Python兼容性问题导致的。
4、type(类名, 父类的元组(针对继承的情况,可以为空),包含属性的字典(名称和值))
5.类由type创建,创建类时,type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)
6.对象由类创建,创建对象时,类的__init__方法自动执行,对象()执行类的 __call__ 方法
"""

"""
# 元类的使用
class SingletonType(type):
def __init__(self, *args, **kwargs):
super(SingletonType, self).__init__(*args, **kwargs)

def __call__(cls, *args, **kwargs): # 这里的cls,即Foo类
print('cls', cls)
obj = cls.__new__(cls, *args, **kwargs)
cls.__init__(obj, *args, **kwargs) # Foo.__init__(obj)
return obj


class Foo(metaclass=SingletonType): # 指定创建Foo的type为SingletonType
def __init__(self, name):
self.name = name

def __new__(cls, *args, **kwargs):
return object.__new__(cls)


obj = Foo('xx')
"""
# 单例实现

import threading


class SingletonType(type):
_instance_lock = threading.Lock()

def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with SingletonType._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
return cls._instance


class Foo(metaclass=SingletonType):
def __init__(self, name):
self.name = name


obj1 = Foo('name')
obj2 = Foo('name')
print(obj1, obj2)

猜你喜欢

转载自www.cnblogs.com/Xingtxx/p/12814940.html