面向对象知识点4

面对对象知识点

单例模型

​ 按照我的理解来说就是,一间酒店(内存地址相同)有分为若干个相同的房间住着相同或不同的客人,就是大家都住这同一家酒店。

  1. 通过类调用类的方法@classmethod实现
name = 'wq'
age = 18

class Foo:
    __instance = None
    def __init__(self,name,age):
        self.name = name
        self.age = age

    @classmethod
    def func(cls):
        if cls.__instance:
            return cls.__instance
        obj = cls(name,age)
        cls.__instance = obj

        return cls.__instance



f = Foo('21','21').func()
f1 = Foo('123','213').func()

#id相同
print(id(f),id(f1)) #230682852827 #22306828528272

  1. 通过装饰器@deco实现
name = 'wq'
age = 18
**
def deco(cls):
    cls.__instance = cls(name,age)y
    def wrapper(*args,**kwargs):
        if len(args) == 0 and len(kwargs) == 0:
            return cls.__instance
        return cls(*args,**kwargs)
    return wrapper
**
@deco
class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age

f = Foo()   #wrapper()

print(f.__dict__,id(f))   #{'name': 'wq', 'age': 18}    #1967167266544

f1 = Foo()

print(f.__dict__,id(f))    #{'name': 'wq', 'age': 18}    #1967167266544 

3.通过元类实现

name = 'wq'
age = '18'

class Mymeta(type):
    def __init__(self,class_name,class_bases,class_dic):
        super(Mymeta, self).__init__(class_name,class_bases,class_dic)

        self.__instance = self(name,age)

    def __call__(self, *args, **kwargs):

        if len(args) == 0 and len(kwargs) == 0:
            return self.__instance

        obj = self.__new__(self)
        self.__init__(obj,*args,**kwargs)
        return obj

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

f = Foo()

print(f.__dict__,id(f))     #{'name': 'wq', 'age': '18'} 2243990642760


f1 = Foo()

print(f1.__dict__,id(f1))   #{'name': 'wq', 'age': '18'} 2243990642760
posted @ 2019-06-23 22:21  wanjiang  阅读(93)  评论(0编辑  收藏  举报