usual_module and decorate_learning ang class_decorate

常用模块

"""
python解释器中带得常用模块
sys
os
random
re
math
urllib
builtins
time
"""

import sys
#sys系统的意思: python解释器相关的
#搜索模块的路径
print(sys.path)
#win32: windows平台
print(sys.platform)
#python解释器的版本
print(sys.version)
#牵扯的模块
print(sys.modules)

# print(sys.ps1): 针对在python解释器中的命令行中使用
#python usual_module.py
"""
import sys
print(sys.argv)
print(sys.argv[0], sys.argv[1], sys.argv[2])
"""

import os  #就是和操作系统相关的
#operation system: 操作系统: Linux, Windows, Unix, Mac

print(os.environ)
print(os.name)
#. V, F, M, 文件:
#V: variable, F: funciton, M: method, 文件:子模块
print(os.curdir)
print(os.altsep)
print(os.defpath)
# print(os.)

# print(os.curdir)
# os.chdir("D:\\test")
# print(os.curdir)
# print(os.listdir("."))

#使用递归去列出当前目录下的所有文件(格式要求:分层输出)
#listdir(): 可以列出当前目录下有多少文件(目录和文件)
#chdir(): 切换到指定目录
#判断什么是目录,什么是文件
#os.mkdir(path, mode) => mode:权限,path:路径
#os.rmdir(): => 删除

#os.path.join(path, *path): 使用固定的符号去连接路径
#\ , /
print(os.path.join("D:\\test", "test2", "test3"))
#只分割路径最后一层
print(os.path.split("D:\\test\\test2\\test3\\test3.txt"))
print(os.path.split("D:\\test\\test2\\test3"))
print(os.path.basename("D:\\test\\test2\\test3"))
print(os.path.basename("D:\\test\\test2\\test3\\test3.txt"))
print(os.path.isabs("."))
print(os.path.isabs("D:\\lwz_data\\openlab\\20210816Python"))
print(os.path.isdir("D:\\test\\test2\\test3"))
print(os.path.isdir("D:\\test\\test2\\test3\\test3.txt"))
print(os.path.isfile("D:\\test\\test2\\test3\\test3.txt"))
print(os.path.isfile("D:\\test\\test2\\test3"))
print(os.path.abspath("."))
print(os.path.dirname("D:\\test\\test2\\test3\\test3.txt"))
print(os.path.getsize("D:\\test\\test2\\test3\\test3.txt"))
print(os.path.exists("D:\\test\\test8"))
# os.path.realpath()
"""
atime:access time: 最后一次访问时间
ctime:change time: 更改状态:权限,所有者.所属组
mtime:modify time: 修改内容
linux中ll / ls -l 显示的是什么时间:mtime
"""

# import random
# from random import random
from random import random, choice, choices, sample, randint
# from random import random as ran

#随机数[0, 1)之间的小数
print(random())
print(randint(0, 100))
print(choice([4, 2, 3, 8]))
print(choices([4, 2, 3, 8], k=3))
# sample(self, population, k, *, counts=None):
# choices(self, population, weights=None, *, cum_weights=None, k=1):
#choices
#sample
# 80 => 随机出8个分数 =》 8个分输之和/8 = 80,
# 8个分数的分布,70 - 90之间 =》 score - 10 < score < score + 10


import time #和时间相关的

time.sleep(2)

print(11111)

装饰器

"""
在计算机科学中,闭包(英语:Closure),又称词法闭包(Lexical Closure)或
函数闭包(function closures),是引用了自由变量的函数。

#自由变量
#全局变量
#局部变量

这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。
所以,有另一种说法认为闭包是由函数和与其相关的引用环境组合而成的实体。
"""

c = 2


def func(b):  # b:函数的形参  func: 绑定
    a = 3
    print(a)
    print(b)
    # 绑定操作
    # 定义要在调用之前


# NameError: name 'a' is not defined
# UnboundLocalError: local variable 'a' referenced before assignment
func(1)

"""
可见型与绑定:
code block: 代码块:if, for, while, 函数, 类, 模块, 异常
scope: 作用域,在code block中定义name的可见性
block's environment: 执行的环境
bind name: 绑定操作
    变量定义:打标签的操作,即是一种绑定操作
    for循环中的:for 变量 in:变量也是一种绑定操作
    异常:异常中的变量定义
    函数的形参:
    函数的定义: 函数名和函数对象关联起来
    类的的定义: 类名和类关联起来
local variable: 局部变量,在block中被绑定
global variable: 模块中,或者使用global
free variable: 在一个block中被引用,但是未在block中定义
可见性与可引用:
不可见: 你在代码块中未有绑定的操作
可见的: 在代码块中有绑定的操作,可见不一定可引用, 只有引用在定义才可以

总的来说就是在一个code block中,所有绑定操作中被绑定的name均可以视为一个local variable;
但是直到绑定操作被执行之后才可以真正的引用该name。



python中作用域搜索的规则:
最先搜索的最内部作用域包含局部名称
#离他最近的范围进行搜索: 函数内部, 函数内部搜索到a了

从最近的封闭作用域开始搜索的任何封闭函数的作用域包含非局部名称,也包括非全局名称
#搜索自由变量

倒数第二个作用域包含当前模块的全局名称
#在模块中搜索全局变量
最外面的作用域(最后搜索)是包含内置名称的命名空间
#搜索内置的全局变量


"""
a = 6


def func2(b):
    a = 4
    print(a)
    print(b)


func2(7)
print(a)


# a = 6
# def func2(b):
#     print(a)
#     print(b)


# 输出:4, 7 => 为什么不是6, 7

def outer():
    data = "Outer"

    def inner():
        print(f"Print {data} in inner")

    return inner


# inner函数中有没有定义data这个变量? 没有
# 那我inner中可不可以应用data这个变量? 可以引用
# 如果可以引用,为什么呢?
# 搜索步骤:
# 1.inner中查找本地变量(local variable), 发现没找到
# 2. 在外层函数中搜索data变量, 有data变量
#    既然inner没有定义这个data变量,outer的局部变量,自由变量(非局部名称)
inner = outer()
inner()
print(inner.__code__.co_cellvars)
print(inner.__code__.co_freevars)  # inner中的自由变量
print(outer.__code__.co_cellvars)  # outer中局部变量


# 闭包特征:
# 肯定是嵌套函数
# 内层函数引用外层函数的变量: 自由变量和内层函数是同时存在的
# 在外层函数中返回了内层函数

def avg():
    data = []

    def averager(value):
        data.append(value)
        avg_value = sum(data) / len(data)
        print(avg_value)

    return averager


averager = avg()
averager(10)
averager(11)
averager(12)
averager(13)


def avg2(list_data):
    avg_value = sum(list_data) / len(list_data)
    print(avg_value)


avg2([1, 2, 3, 4])

# 装饰器: 完全利用了闭包原理,在它的基础有所改动.
# 装饰器的作用:在于它在不改变原函数的情况,去增强原函数的功能
#             装饰器本质上是⼀个python函数,
#             它可以在让其他函数在不需要做任何代码的变动的前提下增加额外的功能
# 装饰器的应用:计算函数的运行时间
"""
装饰器怎么来用呢?
语法糖: @装饰器名称
装饰器是一个函数,被装饰的也是一个函数
如何去定义一个装饰器:
   1.是一个函数
   2.函数的参数:因为我们要装饰的是一个函数,所以参数是待装饰的函数对象
   3.利用闭包的原理:使用自由变量
   4.嵌套函数
     外层函数:只传了一个函数对象(待装饰函数)
     内层函数:func(): 可以执行原函数
              执行之前,或者, 在执行之后,去做额外的事情
   5.外层函数返回值是内层函数

"""


def my_decorator(func):
    data = func

    def decorator():
        print("Before Action")
        data()
        print("After Action")

    return decorator


# 原函数
# @my_decorator
def to_decorated():
    print("Original Function")


# my_decorator()

print(my_decorator.__code__.co_cellvars)

# to_decorated()
decorated = my_decorator(to_decorated)
decorated()
print(my_decorator.__code__.co_cellvars)

"""
作业1:
定义一个类:Person类, name , age
person = Person("", 19)

print(person) => "My name is xxx, age is xx"
bool(person) => 返回False
len(person) => 1024
person2 = Person("", 20)
person == person2 #如果两个年龄相等返回True, 不相等返回False
person < person2  #如果person年龄> person2的年龄,返回False, 否则 返回True

person + person2: 返回: person的名字和person2的名字

作业2:
定义一个装饰器:计算函数执行时间: 使用模块time

time.sleep(2)
#计算函数运行时间;
import time
print(time.time())
time.sleep(2)
print(time.time())
"""

类装饰器

class Logger:
    #获取到func
    def __init__(self, func):
        self.func = func
    #实例化对象
    #执行这个对象-> __call__
    #所以函数的参数也是在这个时候传入
    def __call__(self, *args, **kwargs):
        print("before action")
        self.func(*args, **kwargs)
        print("after action")
# logger = Logger()

# logger() #如果一个对象可调用,那意味着它实现了__call__这个方法
# print(callable(logger)) #callable:是否可调用
# data = 1
# # data()

# print(callable(data))
@Logger
def test_func(arg1, arg2):
    print(arg1, arg2)

test_func(1, 2)
# logger = Logger(test_func)
# logger(1, 2)

"""
test_func(1, 2)
=> logger = Logger(test_func)
=> logger(1, 2) => __call__(1, 2)
函数装饰器:不同的是,他是将func参数,作为初始化的参数传入
实例化一个对象logger之后:拿到了func
执行实例化对象 logger(1, 2) => 1, 2参数,目标是传递给func 
logger(1, 2) => __call__(1, 2) => 完成装饰器的功能
"""

"""
函数装饰器:主要是利用了闭包
类装饰器:__init__, __call__
"""
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值