Jean's Blog

一个专注软件测试开发技术的个人博客

0%

Python初识

Python两大特性

Python 语言使用率越来越高,使用 Python 不仅可以做 GUI 开发、Web 开发,还能进行数据预处理、数据探索性分析(EDA),更是进行数据挖掘、机器学习、深度学习等的首选语言。

Python是一门什么样的语言呢?这就说到了Python语言的两大特性:

  • 动态语言
  • 强类型语言

看到上面动态和强类型是什么意思呢?下面我们可以结合目前流行的语言的特点,进行分类说明。

动态语言

要了解什么是动态语言,要首先了解“类型检查”。

类型检查是验证类型约束的过程,编译器或解释器通常在编译阶段运行阶段类型检查

类型检查就是查看“变量”和它们的”类型”,然后判断表达式是否合理。例如,不能拿一个 string 类型变量除以浮点数变量。

  • 类型检查发生在程序运行阶段(run time),那么它便是“动态类型语言”(dynamically typed languages)。常见的动态语言包括:
    • Python
    • JavaScrpit
    • PHP
  • 类型检查发生在编译阶段(compile time),是“静态类型语言”(statically typed languages)。常见的静态类型语言包括:
    • C
    • C++
    • Java
    • C#
    • Scala

强类型语言

强类型语言是指:不管是在编译阶段还是运行阶段,一旦某种类型绑定到变量后,此变量便会持有此类型,并且不能同其他类型在计算表达式时,混合使用。

例如,在交互式工具 IPython 中输入如下两行代码:

image-20230524104613183

程序会抛出 TypeError 异常,意思是不支持 int 变量和 str 变量相加。常见的强类型语言有:

  • Python
  • Java
  • C#
  • Scala

已讲了强类型语言,则与之对应的是弱类型语言,那么我们现在可以理解,弱类型语言就是可以将其他数据类型进行混合计算。例如,弱类型语言代表 JavaScript,支持如下操作:

1
2
var data = 5
data = data + 'xiaoming' //string 和 int 结合自动转化为 string

常见的弱类型语言有:

  • C
  • C++
  • PHP
  • Javascript

如下,按照是否为静态/动态语言,弱类型/强类型两个维度,总结常用的语言分类。

image-20230524104632822

Python环境管理

Python历史

image-20230524104703311

Python版本选择

  • Python2.x已经是遗产
  • Python3.x是现在和未来的语言

Python的安装

在Mac上安装Python

如果你正在使用Mac,系统是OS X>=10.9,那么系统自带的Python版本是2.7。要安装最新的Python 3.8,有两个方法:

  • 方法一:从Python官网下载Python 3.8的安装程序,下载后双击运行并安装;
  • 方法二:如果安装了Homebrew,直接通过命令brew install python3安装即可。

注:由于MacOS自带了python2,在控制台输入python,则是python2的版本,若想输入python是为python3的版本,则将python3的执行设置一个软连接

1
ln -f /usr/local/bin/python3.8 /usr/local/bin/python

或者,配置环境变量

1
2
3
4
5
6
7
# Setting PATH for Python 3.8
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.8/bin:${PATH}"
export PATH

# 设置别名
alias python="/Library/Frameworks/Python.framework/Versions/3.8/bin/python3.8"

Python IDE之PyCharm

  • PyCharm是一种Python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具
  • 调试、语法高亮、Project管理、代码跳转、智能提示、自动完成、单元测试、版本控制等功能
  • 用于支持Django框架下的专业Web开发

PyCharm的安装

image-20230524104729316

pip依赖管理

pip介绍

  • pip是python中的标准库管理器。它允许你安装和管理不属于python标准库的其它软件包
  • Python3的3.4版本以及Python2的2.7.9版本开始,pip被直接包括在Python的安装包内
  • pypi托管了大量非常流行的库(www.pypi.org)

pip帮助

查看pip帮助文档,pip help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
lvjing@lvjingdeMacBook-Pro ~ % pip help

Usage:
pip <command> [options]

Commands:
install Install packages.
download Download packages.
uninstall Uninstall packages.
freeze Output installed packages in requirements format.
list List installed packages.
show Show information about installed packages.
check Verify installed packages have compatible dependencies.
config Manage local and global configuration.
search Search PyPI for packages.
cache Inspect and manage pip's wheel cache.
index Inspect information available from package indexes.
wheel Build wheels from your requirements.
hash Compute hashes of package archives.
completion A helper command used for command completion.
debug Show information useful for debugging.
help Show help for commands.

General Options:
-h, --help Show help.
--isolated Run pip in an isolated mode, ignoring
environment variables and user configuration.
-v, --verbose Give more output. Option is additive, and can be
used up to 3 times.
-V, --version Show version and exit.
-q, --quiet Give less output. Option is additive, and can be
used up to 3 times (corresponding to WARNING,
ERROR, and CRITICAL logging levels).
--log <path> Path to a verbose appending log.
--no-input Disable prompting for input.
--proxy <proxy> Specify a proxy in the form
[user:passwd@]proxy.server:port.
--retries <retries> Maximum number of retries each connection should
attempt (default 5 times).
--timeout <sec> Set the socket timeout (default 15 seconds).
--exists-action <action> Default action when a path already exists:
(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
--trusted-host <hostname> Mark this host or host:port pair as trusted,
even though it does not have valid or any HTTPS.
--cert <path> Path to PEM-encoded CA certificate bundle. If
provided, overrides the default. See 'SSL
Certificate Verification' in pip documentation
for more information.
--client-cert <path> Path to SSL client certificate, a single file
containing the private key and the certificate
in PEM format.
--cache-dir <dir> Store the cache data in <dir>.
--no-cache-dir Disable the cache.
--disable-pip-version-check
Don't periodically check PyPI to determine
whether a new version of pip is available for
download. Implied with --no-index.
--no-color Suppress colored output.
--no-python-version-warning
Silence deprecation warnings for upcoming
unsupported Pythons.
--use-feature <feature> Enable new functionality, that may be backward
incompatible.
--use-deprecated <feature> Enable deprecated functionality, that will be
removed in the future.

pip使用

Python四大基本语法

分别从变量命名规则、缩进原则、特殊关键字和特殊运算符四个方面,总结 Python 的基本语法。

命名规则

Python 的变量命名规则主要包括两条:

  • 允许包括英文、数字以及下划线(_),不能以数字开头
  • 名称区分大小写

特别说明以“下划线”开头的变量是有特殊意义的:

  • 类变量若以单下划线(_)开头,代表不能直接被访问,类似于 C# 的受保护型变量(protected),表示不能通过 import module_name 而导入。
  • 类变量若以双下划(__)开头,表示为类的私有成员,不能被导入和其他类变量访问。
  • 以双下划开头和双下划线结尾的变量是 Python 里的专用标识,有特殊的身份。

如 Python 自定义类中都包括 initadd 方法,如果不重写 add 去执行两个类加法操作,程序会抛 TypeError 异常。只有重写后,程序才能正常执行加法操作。

Python 变量命名习惯一般遵守蛇形命名法(snake case):

  • 一般变量命名,book_id、book_store_count;
  • 类名首字符为大写,如 Python 内置模块 collections.abc 中的 Iterable 类、我们自定义的 Book 类等;
  • 类方法名:get_store_count();
  • 其他特殊变量,会全部大写,M_PI、MAX_VEHICLE_SPEED。

这与 Java 命名方法不同,Java 最典型的命名方法——驼峰命名法(camel case)。

缩进原则

Python 最具特色的地方就是用缩进代替 Java、C++ 中的 {},缩进的层级结构表示代码的逻辑层次。

比如,自定义一个 Book 类,重写 add 方法计算两类书的库存量和。

Python 的缩进方法,一般为 4 个字符。

  • 代码行 class Book(object) 与代码行 # 定义类的参数 的缩进,此处为 4 个字符;
  • 代码行 def __add__(self,book):return 所在行缩进也是 4 个字符。

通过这种层级结构,展现代码的逻辑层次。

下面代码,创建一个 Book 类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 定义类
class Book(object):
# 定义类的参数
def __init__(self,book_id, book_name, book_store_count):
self.book_id = book_id
self.book_name = book_name
self.book_store_count = book_store_count
# 重写加法操作
def __add__(self,book):
return self.book_store_count + book.book_store_count

# 创建两个 Book 类的实例:
python_intro_book = Book(1,'python入门书',100)
ml_intro_book = Book(2,'机器学习入门书',200)
# 求两本书的总销量
sales_cnt = python_intro_book + ml_intro_book
print(sales_cnt) # 300

如下是代码执行结果的演示图,打印总销量 300。结合图形,辅助大家快速理解代码

image-20230524104803968

缩进格式、行间空行数、变量和等号空格等 Python 编码规范参考PEP8。

autopep8 包遵循 PEP8 的所有规范,安装此包,做好相关配置,便可自动实现 PEP8 制定的编码规范。

特殊关键字

Python 有 35 个关键字:

1
2
3
4
5
6
7
False      await      else       import     pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

自定义变量名不能与它们重复。

常用且不同于其他常用语言 C++ 和 Java 的关键字,如:

  • TrueFalse 用于表示值的真假,在 Java 中是 truefalse
  • 逻辑反操作 Python 使用 not,Java 是 !
  • None 表示空值,Java 使用 null
  • Python 两个条件同时满足使用 and,Java 是 &&
  • 两者满足其一,Python 使用 or,Java 使用 ||
  • Python 使用 elif, Java 是 else if

其他比较特殊的关键字,如:

  • del 用于删除可迭代对象中某个元素;
  • def 用于定义函数;
  • yield 用于定义生成器(generator)函数;
  • globalnonlocal 一种应用是 Python 函数式编程的闭包场景;
  • pass 一种应用是定义接口,也是 Python 语言特有的一个关键字。

特殊运算符

Python 的运算符包括:

1
2
3
+       -       *       **      /       //      %      @
<< >> & | ^ ~ :=
< > <= >= == !=

大部分运算符应该被熟知,重点介绍 3 个比较特殊的://**:=

  • //用于两个数值相除且向下取整,与 Python 的 math 模块中 floor 功能相似:

    1
    2
    3
    4
    >>> 5 // 2
    2
    >>> 5 // 4.5
    1.0
  • **用于幂运算:

    1
    2
    >>> 2 ** 3
    8
  • :=是在 2019 年,Python 3.8 版本里,刚刚才被支持的运算符,被形象地称为“海象运算符”。

    1
    2
    3
    n = len(a)
    if n > 10:
    print(f"{n}大于10")

    如果使用“海象运算符”,写法上更为精简:

    1
    2
    if (n := len(a)) > 10:
    print(f"{n}大于10")

Python 比较运算符还支持链式比较,应用起来更加方便,比如:

1
2
3
4
5
>>> i = 3
>>> print( 1 < i < 3)
False
>>> print( 1 < i <= 3)
True

Python官方文档中函数介绍学习

学习语言的最好方式就是官方提供的文档,每种语言都有内置的函数或者三方函数,在使用时,是通过官方文档或者源码中的描述查看函数的使用,那么,在Python语言中,以几个例子查看函数的使用:

函数介绍实例一

Python内置的max函数使用(官方文档内容),如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).

New in version 3.4: The default keyword-only argument.

Changed in version 3.8: The key can be None.

看到在函数的介绍用,还有这一种用法:max(iterable, *[, default=obj, key=func]) -> value,是否感到很奇怪,max函数的几个形参,为什么有*符号,又有[]?函数原型的文档有如下解释:

  • 函数形参列表中符号 * 表示,后面的形参只能为关键字参数(keyword argument),不能为位置参数(positional argument)

所以,max函数如下的使用:

1
2
3
>>> a = [1, 2, 3, 4, 2, 2, 3]
>>> max(a, key=lambda x: a.count(x), default=1)
2

自定义一个函数,看下*的作用:

1
2
3
4
5
6
7
8
>>> def f(a, *, b):
... pass
...
>>> f(a, b=1)
>>> f(a, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes 1 positional argument but 2 were given

平时大家更多看到的是这么使用 max 函数:

1
2
>>> max([1,2,3,4,2,2,3])
4

[] 表示里面的形参是可选项,max 函数可被如下几种形式调用:

1
2
3
4
max(iterable)
max(iterable,*, key)
max(iterable,*,default)
max(iterable,*, key, default)

不能这么被调用:

1
max(*, key)

iterable 没有默认值,所以它是不能被省略的,必须要给出一个实参。

函数介绍实例二

再看一个内置函数 sum(官方文档内容):

1
2
3
4
5
6
sum(iterable, /, start=0)
Sums start and the items of an iterable from left to right and returns the total. The iterable’s items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling ''.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().

Changed in version 3.8: The start parameter can be specified as a keyword argument.

看到形参列表中有一个 /,它表示 / 前的参数只能是位置参数,不能是关键字参数。

以下调用是合法的:

1
2
3
>>> a = [1, 3, 2, 1, 4, 2]
>>> sum(a, 2)
15

以下调用是非法的,iterable 参数不能被赋值为关键字实参:

1
2
3
4
>>> sum(iterable=a, start=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() takes at least 1 positional argument (0 given)

保留关键字

Python3.6(33个) Python3.8(35个,相比3.6新增了’async’,’await’)

False None True and as assert async await break class continue def del if elif else except finally for from global import in is lambda nonlocal not or pass raise return try while with yield