元类

作者: 她即我命 | 来源:发表于2018-12-01 15:44 被阅读8次
    """
    元类 - 描述类的类 - metaclass
    """
    import sys
    
    
    class SingletonMeta(type):
        
        def __init__(cls, *args, **kwargs):
            cls.__instance = None
            super().__init__(*args, **kwargs)
    
        def __call__(cls, *args, **kwargs):
            if cls.__instance is None:
                cls.__instance = super().__call__(*args, **kwargs)
            return cls.__instance
    
    
    class President(object, metaclass=SingletonMeta):
        __slots__ = ('name', 'year')
    
        def __init__(self, name, year):
            self.name = name
            self.year = year
    
    
    def main():
        p1 = President('奥巴马', 4)
        p2 = President('特朗普', 4)
        # p2.wife = '刘美丽'
        print(p1 == p2)
        print(id(p1), id(p2))
        print(p1.name, p2.name)
        print(sys.getsizeof(p1))
    
    
    if __name__ == '__main__':
        main()
    
    

    相关文章

      网友评论

          本文标题:元类

          本文链接:https://www.haomeiwen.com/subject/tdhrcqtx.html