廖雪峰Python学习笔记day5
学习笔记day4
# python study day5
# 匿名函数 lambda 参数列表: 返回值表达式
# f = lambda x, y: x*y
# print(f(2,3)) #>>> 6
# 装饰器 decorator,不修改原函数定义,动态增加功能的方式
# def log(func): # 对函数添加打印日志
# def wrapper(*args, **kw): # 匹配任何函数参数形式
# print('call %s():' % func.__name__) # __name__函数属性:获取函数名
# return func(*args, **kw)
# return wrapper
# import time
# @log
# def now():
# print(time.strftime('%Y-%m-%d', time.localtime()))
# now() #>>> call now(): 2020-11-23
# log(now)() #>>>
# call wrapper():
# call now():
# 2020-11-23
# 带参数decorator:
# import functools,time
# def log(text):
# def decorator(func):
# @functools.wraps(func) # 相当于wrapper.__name__=func.__name__
# def wrapper(*args, **kw):
# print('%s %s():' % (text, func.__name__))
# return func(*args, **kw)
# return wrapper
# return decorator
# @log('execute')
# def now():
# print(time.strftime('%Y-%m-%d', time.localtime()))
# now() #>>>
# execute now():
# 2020-11-23
# 打印函数执行时间
# import time, functools
# def metric(fn):
# now = time.time()
# @functools.wraps(fn) # 缺少该项将影响原函数名
# def wrapper(*args, **kw):
# result = fn(*args, **kw)
# print('%s executed in %s ms' % (fn.__name__, time.time()-now))
# return result
# return wrapper
# @metric
# def test(x, y):
# time.sleep(1.005)
# return x*y
# print(test(3,4)) #>>>
# test executed in 1.0050718784332275 ms
# 12
# 偏函数,将原有函数参数固定默认值创建新函数
# int('123', base=8) # 八进制转换,简写 int('123', 8) >>> 83
# def int2(x, base=2): # 该函数默认二进制转换,int()是十进制
# return int(x, base)
# 使用 functools.partial 创建偏函数
# import functools
# int2 = functools.partial(int, base=2)
# print(int2('1010101')) #>>> 85
# 添加固定参数绑定函数
# max2 = functools.partial(max, 10)
# print(max2(5, 6, 7)) #>>> 10
# 模块,一个.py文件就是一个模块,模块之间可以相互调用
# 为避免模块名冲突,引入包,如 mypackage.abc.func
# 每个包下必须有一个__init__.py的文件(可以为空,也可以有代码)
# 标准模块使用
# #!/usr/bin/env/python3 #(可以让该文件直接在Unix/Linux/Mac上运行)
# # -*- coding: utf-8 -*- #(当前文件使用标准utf-8编码)
# 'a test module' # 模块第一个字符串为文档注释
# __author__ = 'your name' # 添加模块作者信息
# /*编写代码*/
# import sys # 引入sys文件
# args = sys.argv # 使用argv模块变量
# 运行python3 hello.py 获得 sys.argv 就是 ['hello.py']
# 运行python3 hello.py Michael 获得 sys.argv 就是 ['hello.py', 'Michael']
# 作用域,public(公开)、private(私有) (python没有做限制,建议约定俗成)
# 特殊变量:__author__、__name__、__doc__……
# _xxx、__xxx、_xxx_ 如_abc、_func_等定义为private不应该直接被引用
# def _private_1(name):
# return 'Hello, %s' % name
# def _private_2(name):
# return 'Hi, %s' % name
# def greeting(name):
# if len(name) > 3:
# return _private_1(name)
# else:
# return _private_2(name)
# 安装第三方模块,通过包管理工具pip完成
# 如安装图像类库 Pillow, 通过windows上命令提示符窗口运行 pip3 install Pillow
# 如果安装速度慢、超时,可以考虑修改为国内镜像数据源
# 如果需要安装模块比较多,可以统一安装Anaconda,内置有许多常用模块
# OOP 面向对象编程,程序的基本单元是对象
# 面向过程编程是函数集合的顺序执行,推荐使用OOP
# class Student(object): # 定义学生类对象,object 继承的父类
# def __init__(self, name, score): # 构造方法,初始化对象,self表示实例本身
# self.__name = name
# self.__score = score # 对象私有属性
# def get_name(self):
# return self.__name
# def set_name(self, name):
# self.__name = name
# def get_score(self):
# return self.__score
# def set_score(self, score):
# self.__score = score
# def print_score(self): # 对象公有方法
# print('%s: %s' % (self.__name, self.__score))
# stu1 = Student('Lily', 99) # 实例化对象
# stu1.print_score() # 调用实例方法
# stu1.__name # 直接访问私有属性不可
# 对__xxx__此类是特殊变量,不是私有属性定义,so不能用__name__命名
# 继承和多态,子承父类,子类可调用/重写父类方法
# class Animal(object):
# def run(self):
# print('Animal is running...')
# class Dog(Animal):
# pass
# class Cat(Animal):
# def run(self):
# print('cat is running...')
# dog = Dog()
# cat = Cat()
# dog.run() #>>> Animal is running...
# cat.run() #>>> cat is running...
# def run_twice(animal): # 对 animal 参数不一定是Animal对象实例,只要有run()即可
# animal.run()
# run_twice(Dog()) #>>> Animal is running...
# run_twice(Cat()) #>>> cat is running...
# dog、cat = Cat() 也是一个类型,相当于 a = list(),
# 可以使用isinstance(cat, Animal)判断 #>>> True
# 动态语言 python 是鸭子类型(file-like object),不像静态语言(如java)强类型限制
# 获取对象类型,type()、isinstance() 推荐使用isinstance()(可判断子父类继承)
# type('abc') == str #>>> True
# import types
# type(fn) == types.FunctionType #>>> True
# type(abs) == types.BuiltinFunctionType #>>> True
# type(lambda x: x) == types.LambdaType #>>> True
# type((x for x in range(10)))) == types.GeneratorType #>>> True
# isinstance(dog, Dog) and isinstance(dog, Animal) #>>> True
# isinstance((1,3), (list, tuple)) # 多类型判断 >>> True
# 获取对象所有属性和方法 dir()
# print(dir('abc')) #>>>
# ['__add__', '__class__', '__contains__', '__delattr__',
# '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
# '__getattribute__', '__getitem__', '__getnewargs__',
# '__gt__', '__hash__', '__init__', '__init_subclass__',
# '__iter__', '__le__', '__len__', '__lt__', '__mod__',
# '__mul__', '__ne__', '__new__', '__reduce__',
# '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
# '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
# 'capitalize', 'casefold', 'center', 'count', 'encode',
# 'endswith', 'expandtabs', 'find', 'format', 'format_map',
# 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal',
# 'isdigit', 'isidentifier', 'islower', 'isnumeric',
# 'isprintable', 'isspace', 'istitle', 'isupper', 'join',
# 'ljust', 'lower', 'lstrip', 'maketrans', 'partition',
# 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
# 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
# 'swapcase', 'title', 'translate', 'upper', 'zfill']
# len('abc') # 等价于 'abc'.__len__()
# hasattr(object, 'x') # 判断对象object是否有属性或方法‘x’
# setattr(object, 'y', 1) # 设置属性‘y’
# getattr(object, 'y') # 获取属性‘y’
# getattr(object, 'y', 404) # 获取失败返回404
学习笔记day6
还没有评论,来说两句吧...