"""
元类 - 描述类的类 - 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()
网友评论