Clean Python第四章元类部分 4-15演示代码修正

class Memo(type):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__cache = {}

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

    def __call__(self, _id, *args, **kwargs):
        if _id not in self.__cache:
            self.__cache[_id] = super().__call__(_id, *args, **kwargs)
        else:
            print("Existing Instance")
        return self.__cache[_id]


class Foo(metaclass=Memo):
    def __init__(self, _id, *args, **kwargs):
        self.id = _id


def test():
    first = Foo(_id="first")
    second = Foo(_id="first")
    print(id(first) == id(second))


if __name__ == '__main__':
    test()
posted @ 2020-03-02 14:25  公众号python学习开发  阅读(178)  评论(0编辑  收藏  举报