安装与管理

安装

  • 安装路径
    |来源 |python安装路径|
    |:---|:----|
    |系统默认| /System/Library/Frameworks/Python.framework/Versions/2.7|
    |brew安装 | /usr/local/Cellar|
    |官网pkg安装 | /Library/Frameworks/Python.framework/Versions/2.7|

  • brew安装

brew search python
brew install python3
## add env variable
export PATH="/usr/local/bin:/usr/local/sbin:$PATH"
  • 升级python版本:
    ~/.bash_profile 中添加
    alias python="/usr/local/Cellar/python@3.7/3.7.10_3/bin/python3.7"
    注意不要直接删除系统默认的旧版本,有的软件可能依赖旧版本,删除会导致部分软件不可用。

版本管理pipenv

Pipenv 集成了 pip 和 virtual environment 的功能,通过创建虚拟环境,可以保证项目之间的的依赖互不干扰。

  • 安装
    pip install --user pipenv, 测试 pipenv --version. 如果安装不生效,通过python -m site --user-base 得到路径$base,然后将路径 $base/bin 加入$PATH中。

基础补充

基本类型

  • int
    • 十进制 print(123) --> 123
    • 二进制. print(0b10) --> 2
    • 八进制 print(0o11) --> 9
    • 十六进制. print(0x11) --> 17
  • bool
    • 首字母大写, True, False
    • 可转为int,print(False + True + True) --> 2
  • 字符串
    • 单引号(单行),双引号(单行),三引号(可跨行)

基本运算

  • 交换
a,b=10,20 # a=10, b=20
a,b=b,a # a,b值交换,运算之后a=20,b=10
  • is, is not 表示引用是否相同
a,b=10,10
print(id(a), id(b), a is b)
list1 = [1,2,3]
list2 = [1,2,3]
print(id(list1), id(list2), list1 is list2)
# 4553735184 4553735184 True
# 4555984640 4555984256 False
  • bool 运算符
    • and, or, not, in ,not in
    print('ab' in 'abcd') #True
    print(not 0)          #True
    print(not False)      #True
    
  • 运算符优先级
    • 算数运算符 > 位运算符 > 比较运算符 > 布尔运算符 > 赋值运算符
  • 一切皆对象,所有对象都有一个bool值。布尔值位False的
    • False; 数值0; None;空字符串;空列表;空元组;空字典;空集合
  • 不可变序列:字符串,元组;可变序列:列表,字典

语句

  • pass语句
    • 什么都不做,只是一个占位符
    • if语句;for-in语句;函数体
  • else 语句
    • if ... else ...
    • 与while/for循环搭配,没有break时执行else语句
    for _ in range(3):
    pwd = input('请输入密码:')
    if pwd == '8888':
        print('密码正确')
        break
    else:
        print('密码不正确')
    

else:
print('三次输入不正确')
```

  • for 循环
#for循环,只需要执行个数
for _ in range(3):
    print("Hello")

内置函数range

  • range(stop); range(start, stop); range(start, stop, step); range(start=0, stop, step=1)
  • 示例
r = range(10)
print(r)  #range(0, 10)   [0,10)
print(8 in r) # True
print(list(r)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

list

  • list操作,索引左边从0开始递增,右边从-1开始递减。
  • list 可存储不同类型对象
  • 切片操作,默认startIndex=0, endIndex=length, step=1。 step为正数,默认start=0, end=length;step为负数,默认start=length,end=0。
list = ['hello', False, 0] # 可存储不同类型对象
print(list[0], type(list[0]))  #hello <class 'str'>
print(list[-1], type(list[-1]))  #0 <class 'int'> 

# 切片操作,默认startIndex=0, endIndex=length, step=1
list = list(range(1,6)) #[1,6), [1,2,3,4,5]
print(list[0:3:2]) # 切片,startIndex = 0, endIndex = 3, step=2, 结果[1,3]
print(id(list) != id(list[0:3:2])) # 切片是一个新对象, 结果True
# step为正数,默认start=0, end=length
# step为负数,默认start=length,end=0
print(list[::-1]) # 逆序打印所有元素, 结果:[5, 4, 3, 2, 1]
print(list[5:0:-1]) #[5, 4, 3, 2], 不包含索引为0的元素
  • 添加
    • append 列表尾部添加一个元素
    • extend 列表末尾至少添加一个元素
    • insert 任意位置添加一个元素
    • 切片 任意位置至少添加一个元素(替换操作)
list1, list2 = [1,2], ['he','hi']
list1.append(list2)
print(list1) # [1, 2, ['he', 'hi']]
list1 = [1,2]
list1.extend(list2)
print(list1) # [1, 2, 'he', 'hi']
list1.insert(1,90)
print(list1) # [1, 90, 2, 'he', 'hi']
list1[1:] = ['end', True]
print(list1)
  • 删除
    • remove 删除第一个指定的元素;若元素不存在,跑出ValueError
    • pop 删除指定index的元素,默认是最后一个;索引不存在,IndexError
    • clear 清空列表
    • del 删除列表
list = [0,1,2,3,4]
list.remove(3)
print(list) # [0, 1, 2, 4]
list.pop(1)
print(list) #[0, 2, 4]
list.pop()
print(list) # [0, 2]

list = [0,1,2,3,4]
lt = list[1:3] # lt是新对象
print(lt) #[1,2]
list[1:3] = [] #索引[1,3)元素删除
print(list) # [0, 3, 4]
list.clear()
print(list) #[]
  • 修改
list = [0,1,2,3,4]
list[1]=11
print(list) #[0, 11, 2, 3, 4]
list[1:2]=[111,222]
print(list) # [0, 111, 222, 2, 3, 4]
  • 排序
list=[3,2,4,1]
list.sort()
print(list) # [1, 2, 3, 4]
list.sort(reverse=True)
print(list) #[4, 3, 2, 1]
new_list = sorted(list) #返回新列表,原列表不变
print(new_list, list) # [1, 2, 3, 4] [4, 3, 2, 1]
  • 其他
#列表生成式
list = [i*i for i in range(0,6)] #对i执行i*i操作
print(list)

字典

  • Python内置数据结构之一,与列表一样,是可变序列。
  • 字典是无序序列。
dict1 = {'name':'shoren', 'age':20} # {'name': 'shoren', 'age': 20}
dict1 = dict(name='shoren', age=20) # {'name': 'shoren', 'age': 20}
#获取
print(dict1['name']) # shoren
#print(dict1['email']) # KeyError: 'email'
print(dict1.get('email')) #None
print(dict1.get('email', 'abc')) #abc, 提供默认值
# in , not in
print('email' in dict1) # False
# 删除
del dict1['name'] # {'age': 20}
#添加
dict1['email'] = 'abc' # {'age': 20, 'email': 'abc'}
dict1.clear() #清空
  • 遍历
dict1 = {'name':'shoren', 'age':20}
keys = dict1.keys()
print(type(keys), keys) # <class 'dict_keys'> dict_keys(['name', 'age'])
print(list(keys)) #['name', 'age']

values =dict1.values()
print(type(values), values) #<class 'dict_values'> dict_values(['shoren', 20])

items = dict1.items()
print(type(items), items) # <class 'dict_items'> dict_items([('name', 'shoren'), ('age', 20)])
print(list(items)) # [('name', 'shoren'), ('age', 20)]

for item in dict1:
    print(item) # item是key
  • 生成式
keys = ['name','age']
values = ['shoren', 20, 23, 44]
d = {key:value for key, value in zip(keys, values)}
print(d) #{'name': 'shoren', 'age': 20}

元组

t=('hello', 0, True)
t = tuple(('hello', 1, False))
t = (12,) #只包含一个元素,需要加逗号和小括号
t=() #空元组
t=tuple() #空元组
print(type(t)) #<class 'tuple'>
  • 元组不可以修改元素。如果元素是可变类型,则其引用不可改变。
t = (10, [20,30], 0)
#t[1] = 100 #TypeError: 'tuple' object does not support item assignment
t[1].append(40)
print(t) #(10, [20, 30, 40], 0)

集合

  • 无序可变类型
s = {1,2,'Hello',True}
s = set() #空集合
s = set({1,2,3}) #集合,元组,列表,字符串
s = set('python')
print(s) #{'o', 't', 'n', 'h', 'p', 'y'}, 无序
  • 修改操作
    • 元素判断:in 或 not in
    • add 添加一个元素;update批量添加
    • remove(元素不存在,异常), discard(元素不存在,无异常):删除一个元素
    • pop 删除任意一个
    • clear 清空
set = {1,2,3}
set.add(4) #{1, 2, 3, 4}
set.update({4,5}) #{1, 2, 3, 4, 5}
set.remove(3) #{1, 2, 4, 5}
#set.remove(6) #KeyError: 6
set.discard(4) #{1, 2, 5}
set.discard(6) #{1, 2, 5}
set.clear()
  • 集合间的关系
    • 是否相等 == 或 !=
    • 包含关系 issubset 或 issuperset
    • 相交关系 isdisjoint
s1,s2 = {1,2,3},{1,2,3}
print(s1 == s2) #True
print({1,2}.issubset(s1)) #True
print(s1.issuperset(s2))  #True
print(s1.isdisjoint({4,5}))  #True Return True if two sets have a null intersection.
  • 集合数学操作
    Alt text
s1,s2 = {1,2,3}, {2,3,4}
print(s1.intersection(s2), s1&s2) #交集{2, 3} {2, 3}
print(s1.union(s2), s1|s2) #并集 {1, 2, 3, 4} {1, 2, 3, 4}
print(s1.difference(s2), s1-s2) #差集 {1} {1}
print(s1.symmetric_difference(s2), s1^s2) #对称差集{1, 4} {1, 4}
  • 生成式
set1 = {2*i for i in range(5)}
list1 = [2*i for i in range(5)]
dic1 = {key:value  for key, value in zip((1,2,3),(11,22,33))}
print(set1, list1, dic1) # {0, 2, 4, 6, 8} [0, 2, 4, 6, 8] {1: 11, 2: 22, 3: 33}

字符串

  • 字符串驻留机制,值相同的字符串只有一份存储.
  • 拼接字符时,使用join方法,先计算所有字符长度,再进行拷贝,只进行一次new操作。+拼接,效率更低。
a,b,c = 'python',"python", '''python'''
print(id(a)==id(b), a is c) #True True
  • 查找
    • index 子串第一个索引;rindex子串最后一个索引。找不到,抛ValueError。
    • find/rfind 子串第一个/最后一个索引。找不到,返回-1。
s1,s2='jabcdefabc','abc'
print(s1.find(s2), s1.rindex(s2)) #1 7
  • 操作
    • upper 全大写; lower全小写;swapcase 大小写转换;capitalize 首字符大写;title 【每个单词】首字符大写
    • 对齐:center中间对齐;ljust 左对齐; rjust 右对齐;zfill 右对齐,左边用0填充。第一个参数指定宽度,第二个参数指定填充符。
    • split/rsplit 从左边/右边开始分割
    • 切片s[start🔚step]
s='hello'
print(s.center(10, '*'), s.ljust(10,'#')) #**hello*** hello##### 
print(s.center(4, '*')) #长度不够,不用填充 hello
print(s.zfill(6)) #0hello
s='a*b*c*d'
print(s.split(sep='*')) #['a', 'b', 'c', 'd']
print(s.split(sep='*', maxsplit=1)) #['a', 'b', 'c', 'd']

s1 = 'hi, python, python, python'
print(s1.replace('python', 'java')) #hi, java, java, java
print(s1.replace('python', 'java', 2)) #hi, java, java, python, 可指定替换次数
l1,s1,t1 = ['a','b','c'], {'h','i','k'},('x','y','z')
print('$'.join(l1), '*'.join(s1), '-'.join(t1)) # a$b$c h*k*i x-y-z

s='012345'
print(s[:2], s[3:], s[::2]) # 01 345 024
print(s[::-1], s[-4::1], s[-4::-1]) #543210 2345 210
  • 字符串格式化
    • %,{} 两种占位符
print("name=%s, age=%d, score=%f" %('apple', 10, 99.1)) #name=apple, age=10, score=99.100000
print("name={0}, age={1}, score={2}".format('apple', 10, 99.1)) #name=apple, age=10, score=99.1

函数

  • 返回值

    • 不需要返回值,可以省略return
    • 只有一个返回值,返回原值
    • 多个返回值,返回一个元组
  • 函数参数定义

    • 使用*定义个数可变的位置形参,类型是元组。只能有一个。
    • 使用**定义个数可变的关键字形参,类型是字典。只能有一个。
    • 若两者都有,则个数可变的位置形参必须放在前面。
def func1(*args):
    print(args)

print(func1(10)) #(10,)
print(func1(10,20)) #(10, 20)

def func2(**args):
    print(args)

print(func2(a=10)) #{'a': 10}
print(func2(a=10,b=20)) #{'a': 10, 'b': 20}

异常处理

try:
    print([0,1].index(3))
except ValueError as ve:
    print("ValueError", ve)
except BaseException as e:
    print("error")
else:
    print("execute only when there is no exception")
finally:
    print("always execute.")
    
#ValueError 3 is not in list
#always execute.
  • 抛出异常 raise Exception('msg'),捕获异常try ... except Exception as e

  • python是动态语言,在创建对象之后,可以动态的绑定属性和方法
  • 以两个下划线开头的属性,为private,不要访问。dir(instanceName)获取所有属性值,这里的可以访问到private属性。
  • 实例方法,类方法@classmethod,静态方法@staticmethod
    • 实例方法,参数默认有self,可以获取本实例的属性。自动绑定本实例。调用需要初始化示例。
    • @classmethod修饰类方法,第一个参数会自动绑定到类本身。
    • @staticmethod修饰静态方法,不会自动绑定到类。需要手动指定参数。
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    #实例方法,参数默认有self,可以获取本实例的属性。自动绑定本实例
    def info(self):
        print('name=', self.name, ', age', self.age)

    #类方法,第一个参数会自动绑定到类本身
    @classmethod
    def study(cls):
        print('needs study. class=', cls)

    #静态方法,不会自动绑定到类。需要手动指定参数。
    @staticmethod
    def course(courseName):
        print('study course ', courseName)

Student.study() #类直接调用类方法。needs study. class= <class '__main__.Student'>
Student.course('math') #类直接调用静态方法。study course  math

s1 = Student('Ann', 10)
s1.info() #实例方法调用1:使用实例调用。name= Ann , age 10
Student.info(s1) #实例方法调用2:使用类调用,但需要初始化实例。name= Ann , age 10
s1.study() #使用实例调用类方法。needs study. class= <class '__main__.Student'>
s1.course('history') #使用实例调用静态方法。study course  history
  • 继承语法 class className(superclass1, superclass2, ...)
class MiddleStudent(Student):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade
    def info(self):
        super().info()
        print('grade ', self.grade)

ms = MiddleStudent('Ann', 10, 'seven')
ms.info() #name= Ann , age 10  grade  seven

模块

  • 导入模块
    • import 模块名 [as 别名]
    • from 模块名 import 函数/变量/类
  • 以主程序方式运行:if __name__ = '__main__': pass
  • 包与目录区别:包含__init__.py文件的目录称为包。
  • 导入包 import 包名.模块名

文件

  • 注释文件编码 #encoding=gbk
  • 打开文件:open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
    Alt text
  • with语句
    • 可以自动管理上下文资源,无论什么原因跳出with块,都能确保文件正确的关闭,以此来达到释放资源的目的。
    • 若类实现了特殊方法 enterexit, 则该类对象遵守了上下文管理器协议,其实例对象称为上下文管理器。
#with 管理上下文资源, copy文件
with open('log.png', 'rb') as src_file:
    with open('copylog.png', 'rw') as target_file:
        target_file.write(src_file.read())

#自定义上下文管理器
class MyContentMgr:
    def __enter__(self):
        print('call __enter__')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('call __exit__')

    def show(self):
        print("call show")

with MyContentMgr() as mgr: #相当于 mgr = MyContentMgr()
    mgr.show()

'''
call __enter__
call show
call __exit__
'''

os模块

Alt text
Alt text

  • os.walk(path) 遍历路径下所有文件和目录
#打印路径下所有的目录和文件信息
import os
path = os.getcwd()
lists = os.walk(path)
for dirPath, dirName, fileName in lists:
    for dir in dirName:
        print(os.path.join(dirPath, dir))

    for file in fileName:
        print(os.path.join(dirPath, file))

参考

虚拟环境

pip&

pip list #预览当前环境下的依赖包
pip install pipdeptree #安装pipdeptree工具来管理依赖树
pip install pip-autoremove #安装pip-autoremove 工具卸载间接依赖包
pip-autoremove flask -y #完整卸载flask依赖
pipdeptree #查看依赖树
pip freeze > requirements.txt #记录依赖
pip install -r requirements.txt #安装依赖包

pipenv

# 安装命令
pipenv install beautifulsoup4   #在项目所在虚拟环境中安装beautifulsoup4
pipenv install parsel==1.3.1    #安装parsel并指定其版本
pipenv install --dev nose2      #安装nose2包并将其关联为只在开发环境中需要的包

# 卸载命令
pipenv uninstall beautifulsoup4 #在项目所在虚拟环境中卸载beautifulsoup4
pipenv uninstall --all          #从虚拟环境中移除所有已安装的包,但Pipfile.lock文件不受影响
pipenv uninstall --all--dev     #从虚拟环境中卸载所有开发包,并从Pipfile文件中移除这些包

# 更新命令
pipenv update requests          #在项目中更新requests包
pipenv update                   #更新项目中所有的包
pipenv update --outdated        #查看现有包哪些已经过期

#查看命令
pipenv grash                    #显示现有的依赖包
pipenv lock                     #更新Pipfile.lock文件锁定当前环境的依赖版本

#生成requirements.txt文件
pipenv lock -r --dev > requirements.txt
#通过requirements.txt文件安装包
pipenv install -r requirements.txt

conda

  • Anaconda vs Miniconda
    Anaconda is a full distribution of the central software in the PyData ecosystem, and includes Python itself along with the binaries for several hundred third-party open-source projects. Miniconda is essentially an installer for an empty conda environment, containing only Conda, its dependencies, and Python

  • 安装

    • 安装地址 , 下载.pkg文件,双击安装。
    • 不能使用pipenv install 安装,否则执行conda命令,报错:
ERROR: The install method you used for conda--probably either `pip install conda`
or `easy_install conda`--is not compatible with using conda as an application.
If your intention is to install conda as a standalone application, currently
supported install methods include the Anaconda installer and the miniconda
installer.  You can download the miniconda installer from
https://conda.io/miniconda.html.
  • Conda channels
    • the locations where packages are stored. 相当于maven库。
    • default channel, 收费
    • conda-forge free
    • 添加conda-forge,并设置为默认channel
# 创建新环境
conda create --name your_env_name python=3.6
conda create -n your_env_name python=3.7
#查看所有环境和当前环境
conda info -e
#激活虚拟环境
conda activate my-env
# If you want to install from conda-forge
conda config --env --add channels conda-forge
# 为某个指定环境安装包
conda install [-n env_name] package_name
# 复制老环境到新的环境中
conda create --name new_env_name --clone old_env_name
#删除某个环境
conda remove --name your_env_name --all
#将当前环境导出
conda env export > environment.yml
# 建立(导入)新的环境
conda env create -f environment.yml
#查看指定环境的包
conda list -n your_env_name

numpy

代码规范

Type Public Internal
Modules lower_with_under _lower_with_under
Packages lower_with_under
Classes CapWords _CapWords
Exceptions CapWords
Functions lower_with_under() _lower_with_under()
Global/Class Constants CAPS_WITH_UNDER _CAPS_WITH_UNDER
Global/Class Variables lower_with_under _lower_with_under
Instance Variables lower_with_under _lower_with_under (protected) or __lower_with_under (private)
Method Names lower_with_under() _lower_with_under() (protected) or __lower_with_under() (private)
Function/Method Parameters lower_with_under
Local Variables lower_with_under

参考

posted on 2021-08-17 02:28  漫夭  阅读(70)  评论(0编辑  收藏  举报