python cls的使用

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值