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的使用
最新推荐文章于 2024-07-21 02:53:47 发布