「PYTHON」- 概念术语、基础语法

help(paramiko.Transport) # 查看文档
dir(<obj>) # 查看类的方法

01)变量参数:用于存储数据的容器;

WIP

02)数据类型:描述变量可以存储的数据的种类,如整数、浮点数、布尔值等;

Python Data Types
type and isinstance in Python – GeeksforGeeks
Python Sets / Python Lists / Python Dictionaries / Python Tuples

数据类型

Text Type: str
Numeric Types: int, float, complex

Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset

Boolean Type: bool
Binary Types: bytes, bytearray, memoryview

存储数据集的数据类型

List、Set、Tuple、Dictionary:

TypeExampleFeatures
Tuple(1, 2, 3, 4)ordered, unchangeable, allow duplicates
List[1, 2, 3, 4]ordered, changeable, allow duplicates
Set{1, 2, 3, 4}unordered, unchangeable, do not allow duplicates
Dictionary{“a”: 1, “b”: 2, “c”: “3”, “d”: “4”}unordered, changeable, does not allow duplicates

获取变量的数据类型

x = 5
s = "geeksforgeeks"
y = [1,2,3]
print(type(x))  # class 'int'
print(type(s))  # class 'str'
print(type(y))  # class 'list'

03)运算符号:用于对变量进行操作的符号,如加减乘除等;

‘|`

What does the “|” sign mean in Python?
How and where to use Python’s and, or, invert magic methods properly

If the two operands are integers, then it will perform a bitwise or, which is a mathematical operation.

If the two operands are set types, this operator will return the union of two sets.

Additionally, authors may define operator behavior for custom types, so if something.property is a user-defined object, you should check that class definition for an __or__() method, which will then define the behavior in your code sample.

针对某个对象,如果实现 and() 方法,则如下代码等价:

class QueryImpl(object):
    def __or__(self, other):
        return ...

a = QueryImpl(...)
b = QueryImpl(...)
c = a & b

a = QueryImpl(...)
b = QueryImpl(...)
c = a.__or__(b)

`is’ and `==’

https://mimo.org/glossary/python/equality-operator

In Python, == and is are valid operators in boolean expressions but serve different purposes.

The == operator checks if the values of two objects are equal, focusing on the content or data they hold.

The is operator checks for object identity, determining if two references point to the same object in memory.

Q:判断 Object 为 None 应该使用什么?
A:When you compare an object to None, use is rather than ==. None is a singleton object, comparing using == invokes the eq method on the object in question, which may be slower than identity comparison. Comparing to None using the is operator is also easier for other programmers to read.
R:https://codeql.github.com/codeql-query-help/python/py-test-equals-none/

三元运算符 | Ternary Operator

Ternary Operator in Python – GeeksforGeeks

# https://www.cnblogs.com/wanghao123/p/7921654.html
a = x if (x>y) else y

#

a, b = 10, 20

min = a if a < b else b  # 能够嵌套

min = a < b and a or b  # [expression] and [on_true] or [on_false]

min = (b, a) [a < b]
min = {True: a, False: b} [a < b]
min = (lambda: b, lambda: a)[a < b]())

04)控制结构:用于控制程序如何执行的结构,如条件语句、循环语句等;

if

print("This line will be printed.")

x = 1
if x == 1:
    # indented four spaces
    print("x is 1.")

for / while

Accessing the index in ‘for’ loops?

# https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops

for idx, val in enumerate(ints):
    print(idx, val)

05)函数方法:一段可重复使用的代码,用于完成特定的任务;

main

if __name__ = '__main__':
	print("Hello World.")

*identifier and **identifier

If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple.

# Excess positional argument (python 2) example:
def foo(a, b, c, *args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo("testa", "testb", "testc", "excess", "another_excess")

If the form **identifier is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

# Excess keyword argument (python 2) example:
def foo(a, b, c, **args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")

a = testa
b = testb
c = testc
{'k': 'another_excess', 'd': 'excess'}

return

Returning Multiple Values in Python – GeeksforGeeks
The Python return Statement: Usage and Best Practices – Real Python

从函数中,返回多个参数。在 Python 中,我们使用 return Tuple 的方式,从函数中返回多个参数,并直接赋值给变量;

# A Python program to return multiple
# values from a method using tuple

# This function returns a tuple
def fun():
	str = "geeksforgeeks"
	x = 20
	return str, x; # Return tuple, we could also
                   # write (str, x)

# Driver code to test above method
str, x = fun() # Assign returned tuple
print(str)
print(x)

yield

When to use yield instead of return in Python? – GeeksforGeeks
How to Use Generators and yield in Python – Real Python

1)与 return “类似”,但是会从“停止”处继续执行(或者说,继续执行 yield 之后的代码);
2)yield 返回的是 Generator 对象(但是,在使用时,很像可迭代的列表);

如下示例,将演示 yield 的特性:

# 示例一:
def simpleGeneratorFun():
    yield 1
    yield 2
    yield 3

for value in simpleGeneratorFun():
    print(value) # 将顺序打印 1 2 3

# 示例二、使用如下方法,单独调用(与「示例一」类似)
gen = simpleGeneratorFun()
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # 3

# 示例三、与前两种不同
# 每次调用 simpleGeneratorFun() 将返回新的 Generator 对象
print(next(simpleGeneratorFun())) # 1
print(next(simpleGeneratorFun())) # 1
print(next(simpleGeneratorFun())) # 1

如下示例,每次从 i += 1 继续执行:

def nextSquare():
	i = 1;

	# An Infinite loop to generate squares
	while True:
		yield i*i
		i += 1 # 下一次,将从这里继续执行

for num in nextSquare():
	if num > 100:
		break
	print(num)
# 将顺序输出 1 4 9 16 ...

动态方法名

Dynamic Method Call In Python 2.7 using strings of method names – Stack Overflow

通过字符串形式指定方法名:

>>> s = 'hello'
>>> getattr(s, 'replace')('l', 'y')
'heyyo'

Lambda

关于 Python 中的 lambda,这可能是你见过的最完整的讲解

下面是一些 lambda 函数示例:

lambda x, y: x*y                             # 函数输入是 x 和 y,输出是它们的积 x*y
lambda: None                                 # 函数没有输入参数,输出是 None
lambda *args: sum(args)                      # 输入是任意个数的参数,输出是它们的和(隐性要求是输入参数必须能够进行加法运算)
lambda **kwargs: 1                           # 输入是任意键值对参数,输出是 1

08)注释:用于在代码中添加说明性文字,方便其他人理解代码;

What is the proper way to comment functions in Python? – Stack Overflow

in Function:

def test_function(p1, p2, p3):
    """
    test_function does blah blah blah.

    :param p1: describe about parameter p1
    :param p2: describe about parameter p2
    :param p3: describe about parameter p3
    :return: describe what it returns
    """
    pass

09)异常处理:用于处理程序中可能出现的错误或异常情况;

Python Try Except

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

try…except…else…finally

8. Errors and Exceptions — Python 3.9.2 documentation
Manually raising (throwing) an exception in Python – Stack Overflow
python – When to use ‘raise NotImplementedError’? – Stack Overflow

# 抛出异常

raise Exception('I know Python!')
raise NotImplementedError

# 捕获异常

try:
	return True
except ZeroDivisionError:
	print("division by zero!")                                                  # Handling of exception (if required)
except IOError as exc:
	print('An exception flew by!')
else:
	print("result is", result)                                                  # execute if no exception
finally:
	return False                                                                # Some code .....(always executed)

Q:针对 else 的用途?
A:The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement. —— 简而言之,else 是为了避免捕获其他语句产生的相同异常
R:What is the intended use of the optional “else” clause of the “try” statement in Python?

Q:… too broad exception …
A:

import logging

list_of_functions = [f_a,f_b,f_c]
for current_function in list_of_functions:
    try:
        current_function()
    except KnownException:
        raise
    except Exception as e:
        logging.exception(e)

R:https://stackoverflow.com/questions/30442236/how-to-prevent-too-broad-exception-in-this-case

打印异常

python exception message capturing – Stack Overflow

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # work on python 3.x
    logger.error('Failed to upload to ftp: %s', e)

10)编译和解释:编程语言的执行方式,编译将源代码转换为可执行文件,解释直接解释执行源代码;

附录:笔记及相关文章

The Python Tutorial

Python 3.8.1 documentation

正式的语言定义:「The Python Language Reference

使用 C/C++ 编写扩展:「Extending and Embedding the Python Interpreter」「Python/C API Reference Manual

属于词汇表:「Glossary

命令行选项及环境变量:「Command line and environment

命令行中的参数传递:import sys

  • when no script and no arguments are given, sys.argv[0] is an empty string
  • When the script name is given as ‘‘ (meaning standard input), sys.argv[0] is set to ‘-‘
  • When -c command is used, sys.argv[0] is set to ‘-c’
  • When -m module is used, sys.argv[0] is set to the full name of the located module
  • Options found after -c command or -m module are not consumed by the Python interpreter’s option processing but left in sys.argv for the command or module to handle.

交互模式

Interactive Mode

交互式输入编辑和历史替换:「Interactive Input Editing and History Substitution

交互执行:

  • 选项 -c 执行命令
  • 选项 -m 执行模块
  • python -i

Enter Interactive Mode In Python
https://stackoverflow.com/questions/13432717/enter-interactive-mode-in-python

附录:指定文件编码

Working with utf-8 encoding in Python source
Correct way to define Python source code encoding
2.1.4. Encoding declarations

可用的文件编码:「codecs

文件编码:在第二行或者第一行使用:# -*- coding: encoding -*-

根据官方文档所述,只要第一行或者第二行匹配正则表达式 coding[=:]\s*([-\w.]+) 则会被视为编码声明;

所以对于 # -*- coding: utf-8 -*-coding: utf-8才是关键部分;

附录:其他关键字

pass

类似于空代码块({});