元类相关试题(单例)

元类相关试题

一、在元类中控制把自定义类的数据属性都变成大写

class Mymeta(type):
    def __new__(cls, name,bases,dic):
        attr = {}
        for k,v in dic.items():
            if not k.startswith('__'):
                k = k.upper()
                attr[k] = v
            attr[k] = v
        return type.__new__(cls,name,bases,attr)

class People(metaclass=Mymeta):
    school = 'oldgirl'
    addr = 'shanghai'
    def __init__(self,name,age):
        self.name = name
        self.age = age

print(People.SCHOOL)
print(People.ADDR)

二、在元类中控制自定义的类无需init方法

class Mymeta(type):
    def __call__(self, *args):
        obj = self.__new__(self)
        obj.name = 'nick'
        obj.age = 19
        return obj

class People(metaclass=Mymeta):
   pass

p = People()
print(p.name)

三、在元类中控制,把自定义的类的数据属性都放到attr字典中

class Mymeta(type):
    def __new__(cls, name,bases,dic):
        dic2 = {'attr':{}}
        for k,v in dic.items():
            if not k.startswith('__'):
                dic2['attr'][k] = v
        return type.__new__(cls,name,bases,dic2)

class People(metaclass=Mymeta):
    school = 'oldgirl'
    addr = 'shanghai'
    def __init__(self,name,age):
        self.name = name
        self.age = age

print(People.attr['school'])
print(People.attr['addr'])

四、四种方式实现单例模式

## 第一种
PORT = 3306
HOST = '127.0.0.1'

class Sql:
    instance = None
    def __init__(self,port,host):
        self.port = port
        self.host = host
    @classmethod
    def get_sigo(cls):
        if not cls.instance:
            cls.cls(PORT,HOST)
        return cls.instance
## 第二种
PORT = 3306
HOST = '127.0.0.1'

def get_sigo(func):
    instance = None
    def wrapper(*args,**kwargs):
        if len(args) != 0 or len(kwargs) != 0:
            #表示传了参数,生成新对象
            res = func(*args,**kwargs)
            return res
        else:
            nonlocal instance
            if not instance:
                instance = func(PORT,HOST)
            return instance
    return wrapper

@get_sigo
class Sql:
    def __init__(self,port,host):
        self.port = port
        self.host = host
## 第三种
PORT = 3306
HOST = '127.0.0.1'

class Mymeta(type):
    def __init__(self,name,bases,dic):
        # 把实例化好的对象,放到类的名称空间
        self.instance = self(PORT,HOST)
    def __call__(self,*args,**kwargs):
        if len(args) != 0 or len(kwargs) != 0:
            obj = object.__new__(self)
            obj.__init__(*args,**kwargs)
            return obj
        else:
            return self.instance
class Sql(metaclass = Mymeta):
    def __init__(self,port,host):
        self.port=port
        self.host=host
## 第四种
# sigo 文件
# ************************************
PORT = 3306
HOST = '127.0.0.1'
class Sql():
    def __init__(self,port,host):
        self.port=port
        self.host=host

s1=Sql(PORT,HOST)
# ************************************

def test():
    from sigo import s1
    print(s1)
def test2():
    from sigo import s1 as s2
    print(s2)
posted @ 2019-09-04 22:09  SweetJack  阅读(123)  评论(0编辑  收藏  举报