/images/hugo/avatar.png

6.3 循环

循环

/images/linux_mt/linux_mt.jpg

本节我们来学习 bash shell 编程的第三部分循环,包括以下内容:

  1. for 循环
  2. while 循环
  3. until 循环
  4. 循环体内的控制语句 continue, break

1. for 循环

for 循环通过遍历列表的方式执行循环,列表生成有如下几种方式

继承

本章重点

  • 子类化内置类型的缺点
  • 多重继承和方法解析顺序
  • 讨论构建类层次结构方面好的做法和不好的做法

1. 子类化内置类型

版本差异:

  • 在 Python 2.2 之前,内置类型(如 list 或 dict)不能子类化。
  • 在 Python 2.2 之后,内置类型可以子类化了,

子类化内置类型:

6.2 if 和条件判断

if 和条件判断

/images/linux_mt/linux_mt.jpg

本节我们来学习 bash shell 编程的第二部分条件判断,包括以下内容:

  1. 条件测试的实现
  2. 测试表达式
  • 数值测试
  • 字符串测试
  • 文件测试
  • 组合测试
  1. 条件判断语句 if 和 case

1. 条件测试的实现

bash 中测试的实现有两种方式,一是执行命令,并利用命令状态返回值来判断;二是所谓的测试表达式。但是所谓的测试表达式本质上仍然是由特定的测试命令执行,并通过命令状态返回值来判断测试是否满足。条件表达式我的理解只不过是为某些通用的测试目的提供便利。

抽象基类

本章首先介绍了非正式接口(称为协议)的高度动态本性,然后讲解了抽象基类的静态接口声明,最后指出了抽象基类的动态特性:虚拟子类,以及使用 __subclasshook__ 方法动态识别子类

6.1 shell 脚本简介

shell 脚本简介

/images/linux_mt/linux_mt.jpg

本章我们将开始学习 bash shell 编程。bash shell 是一门编程语言,内容庞大,按照课程的设计应该循序渐进逐步深入。但是为便于以后复查参考,会将所有 bash shell 相关的知识放在此章节中。本章我们将学习以下内容:

鸭子类型

1. 协议和鸭子类型

协议:

  • 理解:
    • 在面向对象编程中,协议是非正式的接口,即按照所需的行为实现所需的方法
    • 协议是非正式的,没有强制力,因此如果知道类的具体使用场景,通常只需要实现一个协议的部分
    • eg: 为了支持迭代,只需实现 __getitem__ 方法,没必要提供 __len__ 方法

2. 符合Python风格的序列

2.1 对象表示形式

 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
from array import array
import reprlib
import math
import numbers
import functools
import operator
import itertools  # <1>


class Vector:
    typecode = 'd'

    def __init__(self, components):   # self._components 是“受保护的”实例属性
        self._components = array(self.typecode, components) # 分量保存在一个数组中

    def __iter__(self):
        return iter(self._components) # 支持迭代协议

    def __repr__(self):
        components = reprlib.repr(self._components) # reprlib.repr()获取有限长度表示
        components = components[components.find('['): -1]
        return 'Vector({})'.format(components)

    def __str__(self):
        return str(tuple(self))

    def __bytes__(self):
        return (bytes([ord(self.typecode)]) +
                bytes(self._components))

    def __abs__(self):
        return math.sqrt(sum(x * x for x in self))

    def __bool__(self):
        return bool(abs(self))

    @classmethod
    def frombytes(cls, octets):
        typecode = chr(octets[0])
        memv = memoryview(octets[1: ]).cast(typecode)
        return cls(memv)

reprlib