标签:@class 实例 bsp nbsp 单例 ret 类方法 metaclass foo
# 类方法 class Foo: __only = None def __init__(self, name): self.name = name @classmethod def get_only(cls, *args, **kwargs): if cls.__only is None: cls.__only = cls(*args, **kwargs) return cls.__only obj1 = Foo.get_only(‘tom‘) print(obj1.__dict__) # 结果为 {‘name‘: ‘tom‘} obj2 = Foo.get_only(‘jan‘) print(obj1.__dict__) # 结果为 {‘name‘: ‘tom‘} print(obj2.__dict__) # 结果为 {‘name‘: ‘tom‘} print(obj1 is obj2) # 结果为 True
# 类的__new__方法 class Foo: __only = None def __new__(cls, *args, **kwargs): if cls.__only is None: cls.__only = object.__new__(cls) return cls.__only def __init__(self, name): self.name = name obj1 = Foo(‘tom‘) print(obj1.__dict__) # 结果为 {‘name‘: ‘tom‘} obj2 = Foo(‘jan‘) print(obj1.__dict__) # 结果为 {‘name‘: ‘jan‘} print(obj2.__dict__) # 结果为 {‘name‘: ‘jan‘} print(obj1 is obj2) # 结果为 True
# 元类控制类的实例化 class MyMeta(type): def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) def __init__(self, class_name, class_base, class_dic): super().__init__(class_name, class_base, class_dic) self.__only = None def __call__(self, *args, **kwargs): if self.__only is None: obj = self.__new__(self, *args, **kwargs) self.__init__(obj, *args, **kwargs) self.__only = obj return self.__only class Foo(metaclass=MyMeta): def __init__(self, name): self.name = name obj1 = Foo(‘tom‘) print(obj1.__dict__) # 结果为 {‘name‘: ‘tom‘} obj2 = Foo(‘jan‘) print(obj1.__dict__) # 结果为 {‘name‘: ‘tom‘} print(obj2.__dict__) # 结果为 {‘name‘: ‘tom‘} print(obj1 is obj2) # 结果为 True
# 使用装饰器 def passer(cls): def wrapper(*args, **kwargs): if cls._only is None: _only = cls(*args, **kwargs) cls._only = _only return cls._only return wrapper @passer class Foo: _only = None def __init__(self, name): self.name = name obj1 = Foo(‘tom‘) print(obj1.__dict__) # 结果为 {‘name‘: ‘tom‘} obj2 = Foo(‘jan‘) print(obj1.__dict__) # 结果为 {‘name‘: ‘jan‘} print(obj2.__dict__) # 结果为 {‘name‘: ‘jan‘} print(obj1 is obj2) # 结果为 True
# 通过模块导入 import only_obj obj1 = only_obj._only print(obj1.__dict__) # 结果为 {‘name‘: ‘tom‘} obj2 = only_obj._only print(obj1.__dict__) # 结果为 {‘name‘: ‘tom‘} print(obj2.__dict__) # 结果为 {‘name‘: ‘tom‘} print(obj1 is obj2) # 结果为 True
# 被导入模块 class Foo: def __init__(self, name): self.name = name _only = Foo(‘tom‘)
标签:@class 实例 bsp nbsp 单例 ret 类方法 metaclass foo
原文地址:https://www.cnblogs.com/caoyu080202201/p/12802884.html