In [2]:
# 装饰器应用
from functools import wraps
def decorator_name(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not can_run:
            return "Function will not run"
        return f(*args, **kwargs)
    return decorated
@decorator_name
def func():
    return ('Function is running')

can_run = True
print(func())


Function will not run

In [ ]:
# 授权装饰器
from functools import wraps
def requires_auth(f):
    @wraps(f)
    def decrated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password)
            authenticate()
        return f(*args, **kwargs)
    return decrated

In [3]:
# 日志装饰器
from functools import wraps
def logit(func):
    @wraps(func)
    def with_loggin(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_loggin

@logit
def addition_func(x):
    return x + x

result = addition_func(4)


addition_func was called

In [15]:
# 在函数中嵌入装饰器
from functools import wraps
def logit(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # 打开logfile,并写入内容
            with open(logfile, 'a') as opened_file:
                opened_file.write(log_string + '\n')
        return wrapped_function
    return logging_decorator

@logit()
def myfunc1():
    pass

myfunc1()

@logit(logfile='func2.log')
def myfunc2():
    pass

myfunc2()


myfunc1 was called
myfunc2 was called

In [18]:
# 装饰器类
class logit(object):
    def __init__(self, logfile='out.log'):
        self.logfile = logfile
    
    def __call__(self, func):
        log_string = func.__name__ + " was called"
        print(log_string)
        # 打开logfile写入
        with open(self.logfile, 'a') as opened_file:
            opened_file.write(log_string + '\n')
            
        # 现在,发送一个通知
        self.notify()
    
    def notify(self):
        # logit只打日志,不做别的
        pass
    
@logit()
def func1():
    pass

# 创建一个logit子类,来添加email的功能
class email_logit(logit):
    '''
        一个logit的实现版本, 可以在函数调用时发送email给管理员
    '''
    def __init__(self, email="admin@myproject.com", *args, *kwargs):
        self.email = email
        super(logit, self).__init__(*args, **kwargs)
    
    def notify(self):
        # 发送邮件
        pass


func1 was called

In [19]:
def add(v1, v2):
    return v1 + v2

result = add(1,2)
print(result)

def add2(v1, v2):
    global result
    result = v1 + v2
    
add2(2,3)
print(result)


3
5

In [ ]:
# 多个return值

In [24]:
# 对象变动Mutation
def add_to(num, target=[]):
    target.append(num);
    return target
add_to(1)
add_to(2)
add_to(3)


# def add_to2(num, target=None):
#     if target is None:
#         target = []
#     target.append(num)
#     return target

# add_to2(1)
# add_to2(2)


<class 'list'>
<class 'list'>
<class 'list'>
Out[24]:
[1, 2, 3]

In [ ]:
# __slots__属性
# 不使用__slots__
def MyClass(object):
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()
    
def MyClass2(object):
    __slots__ = ['name', 'identifier']
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()

In [36]:
import ipython_memory_usage.ipython_memory_usage as imu
imu.start_watching_memory()

def MyClass(object):
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier

obj = MyClass("tom")
print(obj)

num = 1024 * 256
x = [MyClass("tom") for i in range(num)]


None
In [36] used 0.1680 MiB RAM in 0.11s, peaked 0.00 MiB above current, total RAM usage 41.37 MiB
In [36] used 0.0000 MiB RAM in 0.21s, peaked 0.00 MiB above current, total RAM usage 41.37 MiB
In [36] used -0.1562 MiB RAM in 0.32s, peaked 0.16 MiB above current, total RAM usage 41.21 MiB
In [36] used 0.0000 MiB RAM in 0.42s, peaked 0.16 MiB above current, total RAM usage 41.21 MiB
In [36] used 0.0000 MiB RAM in 0.52s, peaked 0.16 MiB above current, total RAM usage 41.21 MiB
In [36] used 0.0000 MiB RAM in 0.62s, peaked 0.16 MiB above current, total RAM usage 41.21 MiB
In [36] used 0.0000 MiB RAM in 0.73s, peaked 0.16 MiB above current, total RAM usage 41.21 MiB
In [36] used 0.0000 MiB RAM in 0.83s, peaked 0.16 MiB above current, total RAM usage 41.21 MiB
In [36] used 0.0000 MiB RAM in 0.93s, peaked 0.16 MiB above current, total RAM usage 41.21 MiB
In [36] used 0.0000 MiB RAM in 1.04s, peaked 0.16 MiB above current, total RAM usage 41.21 MiB
In [36] used 0.0000 MiB RAM in 1.14s, peaked 0.16 MiB above current, total RAM usage 41.21 MiB

In [40]:
def MyClass(object):
    def __init__(self, name, identifier):
        self.name = name
        print(identifier)
        self.identifier = identifier
        
my = MyClass("tom")


In [40] used 0.1719 MiB RAM in 0.10s, peaked 0.00 MiB above current, total RAM usage 41.65 MiB
In [40] used 0.0000 MiB RAM in 0.21s, peaked 0.00 MiB above current, total RAM usage 41.65 MiB
In [40] used -0.1719 MiB RAM in 0.31s, peaked 0.17 MiB above current, total RAM usage 41.48 MiB
In [40] used 0.0000 MiB RAM in 0.41s, peaked 0.17 MiB above current, total RAM usage 41.48 MiB
In [40] used 0.0000 MiB RAM in 0.52s, peaked 0.17 MiB above current, total RAM usage 41.48 MiB
In [40] used 0.0000 MiB RAM in 0.62s, peaked 0.17 MiB above current, total RAM usage 41.48 MiB
In [40] used 0.0000 MiB RAM in 0.72s, peaked 0.17 MiB above current, total RAM usage 41.48 MiB
In [40] used 0.0000 MiB RAM in 0.82s, peaked 0.17 MiB above current, total RAM usage 41.48 MiB
In [40] used 0.0000 MiB RAM in 0.92s, peaked 0.17 MiB above current, total RAM usage 41.48 MiB
In [40] used 0.0000 MiB RAM in 1.02s, peaked 0.17 MiB above current, total RAM usage 41.48 MiB
In [40] used 0.0000 MiB RAM in 1.13s, peaked 0.17 MiB above current, total RAM usage 41.48 MiB

In [ ]: