从metaclass到__init__, __new__, __call__到单例模式. 到threading中的with到__enter__, __exit__

从metaclass到__init__, new, __call__到单例模式

到threading中的with到__enter__, exit

到字典hashmap原理的__hash__, eq

到Flask的配置文件__dir__的一些类信息

__add__的原理

获取传入参数的kwargs的技巧, 框架中使用

class Foo(object):

    def __new__(cls, *args, **kwargs):
        # res = kwargs.pop("many")
        res = kwargs.get("many", "")
        print(args)
        print(kwargs)
        print(res)
        return 1
    
# new返回什么, obj就是什么
obj = Foo("url", many=True)
print(obj)
import threading
import time


class Singleton(object):
    lock = threading.RLock()
    instance = None

    def __new__(cls, *args, **kwargs):
        # 当进入语句块时 acquire() 方法会被调用,退出语句块时 release() 会被调用。
        with cls.lock:
            if not cls.instance:
                # 实例化比较耗时, 加大延迟模拟并发, 在上一个还没创建结束下一个请求就进来了
                time.sleep(2)
                cls.instance = super().__new__(cls)
            return cls.instance


def task(arg):
        
    obj = Singleton()
    print(id(obj))

def main():
    for i in range(10000):
        t = threading.Thread(target=task, args=(i,))
        t.start()


if __name__ == "__main__":
    main()
class Foo(object):

    def __init__(self, num):
        self.num = num

    # 相加只是调用了__add__方法, 两个参数分别为相加的两个对象
    def __add__(self, other):
        return self.num + other.n


class Bar(object):
    def __init__(self, n):
        self.n = n

f = Foo(1)
b = Bar(2)

res = f + b
print(res)
发布了140 篇原创文章 · 获赞 53 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44291044/article/details/104623487