python cls的使用

2024-06-15 1136阅读
import threading
class Test:
    # new方法用于创建类的实例
    def __new__(cls, *args, **kwargs):
        print("__new__:", cls.__class__.__name__)
        return object.__new__(cls) # 返回实例给init self参数
    
    # init用于初始化类的实例,实例由new方法传递过来的,即这里self
    def __init__(self):
        print("__init__:", self.__class__.__name__)
        
        
t = Test()
# __new__方法主要用于继承一些固定类型
class MyInt(int):
    def __new__(cls, value):
        return int.__new__(cls, value)
    
    
if None:
    it = MyInt(10)
    print(it)
        
        
from enum import Enum, unique
import enum
@unique
class StrEnum(Enum):
    OK = enum.auto(), "success"
    ERROR = enum.auto(), "fail"
    
    @property
    def code(self):
        return self.value[0]
    @property
    def msg(self):
        return self.value[1]
    
def emsg(name, msg=None):
    if isinstance(name, str):
        return StrEnum.ERROR.code, name
    elif isinstance(name, StrEnum):
        return name.code, name.msg
    return StrEnum.OK.code, StrEnum.OK.msg
print(StrEnum.OK.value)
print(emsg(StrEnum.ERROR))
print(emsg("hello"))
    
    
# 实现单例模式
def Single(cls):
    instances = {}
    lock = threading.RLock()
    def get_instance(*args, **kwargs):
        with lock:
            if cls not in instances:
                instances[cls] = cls(*args, **kwargs)
            return instances[cls]
    return get_instance
class Conf:
    def __init__(self, glb):
        self._glb = glb
        
@Single
class MyConf(Conf):
    def __init__(self, value, glb):
        self.value = value
        Conf.__init__(self, glb)
        
    
@Single
class MyConf1(Conf):
    def __init__(self, value, glb):
        self.value = value
        Conf.__init__(self, glb)
        
@Single
class ConfFactory:
    def __init__(self, glb):
        self._glb = glb
    def instance(self, type):
        if type == 1:
            return MyConf(10, self._glb)
        elif type == 2:
            return MyConf1(20, self._glb)
        
if None:
    conf = ConfFactory(2).instance(1)
    print(conf.value, conf._glb)
    conf1 = ConfFactory(2).instance(2)
    print(conf1.value, conf._glb)
python cls的使用
(图片来源网络,侵删)
VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]