直接上代码
元类
metaclass
metaclass
class MyType(type):
def __init__(self, *args, **kwargs):
print("MyType.__init__")
super().__init__(*args, **kwargs)
def __new__(cls, *args, **kwargs):
print("MyType.__new__")
new_cls = super().__new__(cls, *args, **kwargs)
print(new_cls)
return new_cls
def __call__(self, *args, **kwargs):
"""python实例化一个类时,先调用__new__后调用__init__的原因"""
print("MyType.__call__")
empty_obj = self.__new__(self)
self.__init__(empty_obj, *args, **kwargs)
return empty_obj
class Foo(metaclass=MyType): # Foo是MyType的对象
def __init__(self, name):
print("Foo.__init__")
self.name = name
class Foo2(Foo): # 这个类也是有MyType创建的
pass
if __name__ == "__main__":
# 实例化一个类对象时, 调用的是该类的元类的__call__
foo = Foo("alex")
print(foo.name)
元类实现单例模式
元类中的其它参数
class Spam(metaclass=MyMeta, debug=True, synchronize=True):
pass
https://python3-cookbook.readthedocs.io/zh_CN/latest/c09/p15_define_metaclass_that_takes_optional_arguments.html
装饰器
decorator
decorator
装饰方法
import time
def decorator(function):
def wrapper(*args, **kwargs):
start_time = time.time()
result = function(*args, **kwargs)
end_time = time.time()
print("use time:", end_time - start_time)
return result
return wrapper
@decorator
def func(sleep_time):
time.sleep(sleep_time)
return 0
if __name__ == "__main__":
print("func: ", func)
# func: <function decorator.<locals>.wrapper>
ret = func(1)
"""
使用装饰器装饰后, 调用func()实际上是调用 wrapper()
"""
print(ret)
装饰类
def Domain(domain):
print("enter decorater, domain=", domain)
print("dir(domain)=", dir(domain))
def wrapper(cls):
print("enter wrapper, cls=", cls)
cls.num_of_animals = 10
cls.domain = domain
cls.insert = MysqlMapper.insert
print("类名", cls.__name__, dir(cls.__class__))
print("dir(cls)=", dir(cls))
return cls
return wrapper
@Domain(Animal)
class AnimalDao(BaseMapper):
pass
版权声明:本文为qq_44810930原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。