python初步

30 分钟快速入门

(3.9)

运算

 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
# 除法自动转换为浮点数
35 / 5 # => 7.0

# 向下取整除法
3 // -5 # => -1
-5.0 // 3.0 # => -2.0

# 取模正负与模数相同
-7 % 3 # => 2
7 % -3 # => -2

# 乘方
2 ** 4 # => 16

# 逻辑运算符
True and 0 # => False
not -5 or False # => True

# 大小比较相连
1 < 3 < 2 # => False
1 < 2 < 3 # => True

# if 表达式, 同比较元运算符" ? : "
"python!" if 0 > 1 else "java!" # => java!

# is 表示是否为同个对象; == 表示值是否相同
a = [1,2,3,4]
b = a
b is a # => True
b = [1,2,3,4]
b is a # => False
b == a # => True

# None 是一个对象, 只能用 is 判断
0 is None # => False
None is None # => True

# None, 0, 空字符串, 空列表, 空字典, 空元组都是 False
bool(None) # => False
bool(0) # => False
bool("") # => False
bool([]) # => False
bool({}) # => False
bool(()) # => False

变量

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 输出, 默认以空行结尾, 使用附加参数可改变结尾
print("Hello world", end = "!") # => Hello world!

# 输入, 返回字符串
input_string_var = input("Enter some data: ")

# 自动数据类型, 不用声明
# 数字类型: 整型, 浮点型, 布尔型, 复数型; 布尔型是整型的子类; 不可变类型
a, b, c, d = 20, 5.5, True, 4+3j # 元组解包赋值
print(type(a), type(b), type(c), type(d))
# => <class 'int'> <class 'float'> <class 'bool'> <class 'complex'> 

# 访问未赋值变量会抛出异常
some_unknown_var # => NameError
 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
# 字符串类型 (string), 不可变类型
a = "This is a string"
a[5] = 'c' # => TypeError

# 字符串可以用单引号或双引号
"这是字符串"
'这也是字符串'

# 字符串连接
"Hello " + "World!" # => "Hello World!"
"Hello " "python!" # => "Hello python!" 非变量形式时

# f-srings 格式化字符串, 大括号内可加入任何表达式 (3.6+)
name = "python"
f"{name} is {len(name)} characters long" # => python is 6 characters long

# .format 格式化字符串, 可使用参数或关键字
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
"{name} wants to eat {food}".format(name = "Bob", food = "lasagna")
# => "Bob wants to eat lasagna"

# %s 格式化字符串 (2.5-)
"%s can be %s the %s way" % ("strings", "interpolated", "old")
# => strings can be interpolated the old way
 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
# 列表类型 (list), 可变类型
li = []
other_li = [4, 5, 6]

# 尾插与尾删
li.append(1) # li 为 [1]
li.append(2) # li 为 [1, 2]
li.append(4) # li 为 [1, 2, 4]
li.pop()     # li 为 [1, 2]
li.append(3) # li 为 [1, 2, 3]
li.append(4) # li 为 [1, 2, 3, 4]

# 存取同数组, 从 0 开始, -1 表示取尾
li[0] # => 1
li[-1] # =>4

# 越界存取会抛出异常
li[5] # => IndexError

# 切割 list[begin:end:step], 范围相当于 [begin,end)
li[1:3]     # => [2,3]
li[2:]      # => [3,4]
li[:3]      # => [1, 2, 4]
li[::2]     # => [1,4]
li[::-1]    # => [4, 3, 2, 1]
li2 = li[:] # => li2为[1, 2, 3, 4]
li2 is li   # => False

# 删除指定位置元素
del li2[2]      # => li2 为 [1, 2, 4]
# 删除匹配的第一个元素, 无匹配时抛出异常
li.remove(2)    # => li 为 [1, 3, 4]
li.remove(0)    # => ValueError: 0 is not in the list

# 指定位置插入元素
li.insert(1,2)  # => li 为 [1, 2, 3, 4]
# 获取匹配的第一个元素的位置, 无匹配时抛出异常
li.index(1)     # => 0
li.index(0)     # => ValueError: 0 is not in the list


# 列表相加
li + li_other # => [1, 2, 3, 4, 4, 5, 6]
# 列表拼接
li.extend(li_other) # => li 变为 [1, 2, 3, 4, 4, 5, 6]

# in 判断是否包含值
6 in li_other # => True

# len 获取长度
len(li) # => 7
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 元组类型 (tuple), 不可变类型
tup = (1, 2, 3)
tup[0] # => 1
tup[0] = 3 # => TypeError 抛出异常

# 元素数量为1的元组必须要在末尾加逗号
type((1))   # => <class 'int'>
type((1,))  # => <class 'tuple'>
type(())    # => <class 'tuple'>

# 大部分操作同列表, 更改元素除外
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => true

# 元组解包赋值
a, b, c = (1, 2, 3) # a 为 1, b 为 2, c 为 3
# 扩展解包
a, *b, c = (1, 2, 3, 4) # a 为 1, b 为 [2, 3], c 为 3
# 元组括号可省略
d, e, f = 4, 5, 6
# 交换变量值
e, d = d, e # d 为 5, e 为 4
 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
# 字典类型 (dictionary), 可变类型, 存储 key 和 value 的映射关系
empty_dict = {}
filled_dict = {"one": 1, "two": 2, "three": 3}

# key 必须为不可变类型且无重复值, 为确保 key 被转换为唯一的 hash-value 以用于快速查询
invalid_dict = {[1, 2, 3]: "123"} # => TypeError: unhashable type 'list' 抛出异常
valid_dict = {(1, 2, 3): [1, 2, 3]} # => value 可为任何类型

# in 只能判断字典中是否包含 key
"one" in filled_dict # => True
1 in filled_dict     # => False

# [key] 取值, key 不存在时抛出异常
filled_dict["one"] # => 1
filled_dict["four"] # => KeyError
# 用 .get(key) 避免异常, 不存在时返回默认值, 无默认值时返回 None
filled_dict.get("one", 4)    # => 1
filled_dict.get("four", 4)   # => 4
filled_dict.get("four")      # => None

# 用 .keys() 获取所有 key, 用 .values() 获取所有 value
# 返回可迭代对象, 需要包含在 list() 中以转换为列表
# (3.7-) 无序, (3.7+) 按照插入顺序
list(filled_dict.keys()) # => ["one", "two", "three"] (3.7+)
list(filled_dict.values()) # => [1, 2, 3] (3.7+)

# .setdefault() 在 key 不存在时插入新项
filled_dict.setdefault("four", 5) # => "four": 5
filled_dict.setdefault("four", 4) # => "four": 5

# 用 .update(key, value) 赋值
filled_dict.update("four", 4)
filled_dict["five"] = 5         # 另一种赋值方法

# del 删除项
del filled_dict["five"]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 集合类型 (set), 可变类型, 元素必须为不可变类型, 元素不会重复
empty_set = set()
some_set = {1, 1, 2, 2, 3, 4} # some_set 为 {1, 2, 3, 4}
invalid_set = {[1], 1} # => TypeError: unhashable type 'list' 抛出异常

# 集合运算
other_set = {3, 4, 5, 6}
some_set & other_set # => {3, 4, 5} 取交集
some_set | other_set # => {1, 2, 3, 4, 5, 6} 取并集
some_set - other_set # => {1, 2} 取差集
some_set ^ other_set # => {1, 2, 5, 6} 取对称差集

# 用 .add() 添加元素
some_set.add(5)
# 用 .discard 删除元素
some_set.discard(5)
some_set.discard(6) # => 不会抛出异常
# 用 .copy() 复制集合
filled_set = some_set.copy()
filled_set is some_set # => False

# in 判断元素是否在集合内
5 in some_set # => False

流程控制

 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
# if 判断
some_var = 5
if some_var > 10:
    print("some_var is bigger than 10.") # 4个空格缩进
elif some_var < 10:
    print("some_var is smaller than 10.")
else:
    print("some_var is indeed 10.")

# for 循环
for animal in ["dog", "cat", "mouse"]:
    print("{} is a mammal".format(animal))
for i in range(4) # 遍历 0, 1, 2, 3
for i in range(4, 8) # 遍历 4, 5, 6, 7
for i in range(4, 8, 2) # 遍历 4, 6
animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
    print(i, value, end = ", ") # => 0 dog, 1 cat, 2 mouse, 

# while 循环
x = 0
while x < 4:
    print(x)
    x += 1

# 异常处理
try:
    raise IndexError("This is an index error")
except IndexError as e:
    pass # 此处应处理错误
except (TypeError, NameError):
    pass # 可同时处理不同类错误
else:
    print("All good!")
finally:
    print("We can clean up resources here.")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
contents = {"aa": 12, "bb": 21}
with open("file1.txt", "w+") as file:
    file.write(str(contents)) # 字符串写入文件
with open("file2.txt", "w+") as file:
    file.write(json.dumps(contents)) # 对象写入文件
with open("file1.txt", "r+") as file:
    contents = file.read() # 读取文件字符串
print(contents)
with open("file2.txt", "r+") as file:
    contents = json.load(file) # 读取文件对象
print(contents)

# windows 调用 open() 默认为 ANSI
# 读写 utf-8 需指定 encoding = "utf-8"
 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
# 可迭代对象 (iterable) : 可遍历, 但不能随机访问, 可以生成迭代器
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable)
for i in our_iterable: # 遍历可迭代对象
    print(i)
our_iterable[1] # TypeError 抛出异常
our_iterator = iter(our_iterable) # 生成迭代器

# 迭代器 (iterator) 可以记住遍历位置对象
print(next(our_iterator)) # => one
print(next(our_iterator)) # => two
print(next(our_iterator)) # => three
print(next(our_iterator)) # => StopIteration

# for 内部实现了迭代
our_iterator = iter(our_iterable)
for i in our_iterator:
    print(i)

# 可用 list 一次性取出可迭代对象或迭代器所有元素
list(filled_dict.keys())  # => ["one", "two", "three"]
list(our_iterator)  # => []

# 生成器 (generator), 实现惰性运算, 只有在需要时计算下一个值
values = (-x for x in [1, 2, 3, 4, 5])
gen_to_list = list(values)
print(gen_to_list)   # => [-1, -2, -3, -4, -5]

# 生成器函数中 yield 返回并暂停迭代
def fib(n):
    prev, curr = 0, 1
    while n > 0
        max -= 1
        yield curr
        prev, curr = curr, prev + curr

iterator

函数

 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
# def 定义函数
def add(x, y):
    print("x is {} and y is {}.".format(x, y))
    return x + y
add(5, 6)
add(y = 6, x = 5) # 关键词参数可为任意顺序

# 可变参数函数
def varargs(*args): # * 展开元组
    return args
varargs(1, 2, 3) # => (1, 2, 3)
def keyword_args(**kwargs): # ** 展开字典
    return kwargs
keyword_args(big = 1, small = 0) # => {"big": 1, "small": 0}
def all_args(*args, **kwargs): # 混用参数
    print(args, end = ", ")
    print(kwargs)
args = (1, 2, 3, 4)
kwargs = {"a": 1, "b": 2, "c": 3}
all_args(*args) # => (1, 2, 3, 4), {}
all_args(**kwargs) # => (), {"a": 1, "b": 2, "c": 3}
all_args(*args,**kwargs) # => (1, 2, 3, 4), {"a": 1, "b": 2, "c": 3}

# 返回元组
def swap(x, y):
    return y, x
x, y = 1, 2
x, y = swap(x, y) # => x = 2, y = 1

# 函数作用域
x = 5
def set_x(num):
    x = num
def set_global_x(num):
    global x
    x = num
set_x(0)
print(x) # => 5
set_global_x(1)
print(x) # => 1

# 函数是 "一等公民"
def create_adder(x):
    def adder(y):
        return x + y
    return adder
add_10 = create_adder(10)
add_10(3) # => 13

# 匿名函数
func1 = lambda x: x > 2
func2 = lambda x, y: x ** 2 + y ** 2
func1(3) # => True
func2(2, 1) # => 5

# 高阶函数: map 映射, filter 过滤
list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]

# 推导式: 列表, 字典, 集合
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# 模块本质为python文件
# 导入模块
import math
math.sqrt(16) # => 4.0

# 导入模块中的具体函数
from math import ceil, floor
ceil(3.9) # => 4.0
floor(3.9) # => 3.0

# 模块名称简化
import math as m
m.sqrt(16) # => 4.0

# 查看模块中的函数和字段
import math
dir(math)

# 模块重名时, 本地文件优先级高于内建库
 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
# 函数闭包: 返回的子函数调用外层函数变量
def outer(x)
    def inner(y):
        return x + y
    return inner

# 装饰器: 利用函数闭包思路, 在不改变原函数下添加新功能
from functools import wraps

def beg(target_function):
    @wraps(target_function)
    def wrapper(*args, **kwargs):
        msg, say_please = target_function(*args, **kwargs)
        if say_please:
            return "{} {}".format(msg, 'Please! I am poor :(')
        return msg

    return wrapper

@beg
def say(say_please = False):
    msg = 'Can you buy me a cup of coffee?'
    return msg, say_please

print(say())                        # => "Can you buy me a cup of coffee?"
print(say(say_please = True))       # => "Can you buy me a cup of coffee? Please! I am poor :("

 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
66
67
68
69
70
71
72
73
74
class Human:
    
    # 公共属性
    height = 0
    # 私有属性
    __species = 'H. sapiens'

    # 特殊方法: __init__, __del__, __repr__ 等
    def __init__(self, name):
        # 参数赋值给实例的 name 字段
        self.name = name
        # 初始化属性
        self._age = 0
    
    # 实例方法, 第一个参数总是self, 即实例对象
    def say(self, msg):
        print("{name}: {message}".format(name = self.name, message = msg))
    # 私有方法
    def __sing(self):
        return 'yo, yo, check it out...'

    # 类方法, 被所有此类实例共用
    @classmethod
    def get_height(b):
        return b.height
    @classmethod
    def get_species(a):
        return a.__species

    # 静态方法, 没有实例或类的绑定
    @staticmethod
    def grunt():
        return '*grunt*'

    # 同名只读属性
    @property
    def age(self):
        return self._age
    # 允许属性被修改
    @age.setter
    def age(self, age):
        self._age = age
    # 允许属性被删除
    @age.deleter
    def age(self):
        del self._age

# 重载运算符方法: __add__, __sub__, __mul__, __mod__ 等

# 代码块指挥在模块为主程序时被执行
if __name__ == '__main__'

    # 定义实例
    i = Human(name="Ian")
    i.say("hi")                 # => "Ian: hi"

    # 调用类方法
    i.say(i.get_species())      # => "Ian: H. sapiens"
    i.say(i.get_height())       # => "Ian: 0"

    # 修改类属性
    Human.height = 170          # => 公有属性可以外部修改
    i.say(i.get_height())       # => "Ian: 170"
    Human.__species = 'cat'     # => 私有属性不会被外部修改
    i.say(i.get_species())      # => "Ian: H. sapiens"
    
    # 静态方法
    print(Human.grunt())        # => "*grunt*"
    print(i.grunt())            # => "*grunt*"

    # 更新实例属性
    i.age = 24
    i.say(i.age)                # => "Ian: 24"
    del i.age                   # => AttributeError, 抛出异常
 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
# 上述代码存在 human.py 中
from human import Human

# 子类 (继承): 私有对象不能被继承(调用/重载)
class Superhero(Human):
    
    # 重载父类公有属性
    height = 2000

    # 重载构造方法
    def __init__(self, name, movie = False,
                superpowers = ["super strength", "bulletproofing"]):
        self.fictional = True
        self.movie = movie
        self.superpowers = superpowers
        # 调用父类的构造方法
        super().__init__(name)

    # 新增方法
    def boast(self):
        for power in self.superpowers:
            print("I wield the power of {pow}!".format(pow=power))

if __name__ == '__main__':
    sup = Superhero(name = 'Tick')

    if isinstance(sup, Human):      # => True
        print("I am human")
    if type(sup) is Superhero:      # => True
        print("I am superhero")
    
    # 获取方法解析顺序
    print(Superhero.__mro__)        # => (<class '__main__.Superhero'>,
                                    # => <class 'human.Human'>, <class 'object'>)

    # 继承属性
    sup.age = 30
    print(sup.age)      # => 30
    # 子类独有属性
    print("Am I Oscar eligible?" + str(sup.movie))

    # 父类方法子类属性
    print(sup.get_height)   # => 2000
    # 子类独有方法
    sup.boast()         # => I wield the power of super strength!
                        # => I wield the power of bulletproofing!
 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
# 上述代码存在 superhero.py 中
from superhero import Superhero

# 定义另一个父类
class Bat:
    __species = 'Baty'
    # 同样有 height 属性
    heigt = 20

    def __init__(self, can_fly = True):
        self.fly = can_fly

    # 同样有 say 方法
    def say(self, msg):
        msg = '... ... ...'
        return msg
    
    def sonar(self):
        return '))) ... ((('

# 多继承
class Batman(Superhero, Bat):
    def __init__(self, *args, **kwargs):
        Superhero.__init__(self, 'anoymous', movie = True,
                        superpowers = ['Wealthy'], *args, **kwargs)
        Bat.__init__(self, *args, can_fly = False, **kwargs)
        self.name = 'Sad Affleck'

if __name__ == '__main__':
    sup = Batman()

    print(Batman.__mro__)       # => (<class '__main__.Batman'>,
                                # => <class 'superhero.Superhero'>,
                                # => <class 'human.Human'>,
                                # => <class 'bat.Bat'>, <class 'object'>)

    # 属性/方法重复时, 顺序继承
    print(sup.get_height())     # => 2000
    sup.say('I agree')          # => "Sad Affleck: I agree"

    print(sup.sonar())          # => "))) ... ((("
    
    sup.age = 100
    print(sup.age)              # => 100

    # 继承属性重载
    print('Can I fly? ' + str(sup.fly))     # => Can I fly? False
Licensed under CC BY-NC-SA 4.0
最后更新于 2023-10-24
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计