8.1. 语法错误
语法错误又称解析错误。
解析器会重复出错的行并显示指向检测到错误的位置的小箭头。
请注意这并不一定是需要被修复的位置。
8.2. 异常
即使语句或表达式使用了正确的语法,执行时仍可能触发错误。执行时检测到的错误称为 异常 。
内置异常 列出了内置异常及其含义。
语法错误又称解析错误。
解析器会重复出错的行并显示指向检测到错误的位置的小箭头。
请注意这并不一定是需要被修复的位置。
即使语句或表达式使用了正确的语法,执行时仍可能触发错误。执行时检测到的错误称为 异常 。
内置异常 列出了内置异常及其含义。
模块是包含 Python 定义和语句的文件。其文件名是模块名加后缀名 .py
。在模块内部,通过全局变量 __name__
可以获取模块名(即字符串)。
# 斐波那契数列模块
def fib(n):
"""Write Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
def fib2(n):
"""Return Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a + b
return result
对输出格式的控制不只是打印空格分隔的值,还需要更多方式。格式化输出包括以下几种方法。
使用 格式化字符串字面值 ,要在字符串开头的引号/三引号前添加 f
或 F
。
在这种字符串中,可以在 {
和 }
字符之间输入引用的变量,或字面值的 Python 表达式。
year = 2016
event = 'Referendum'
f'Results of the {year} {event}'
# 'Results of the 2016 Referendum'
字符串的 str.format()
方法需要更多手动操作。
你仍将使用 {
和 }
来标记变量将被替换的位置并且可以提供详细的格式化指令,但你还需要提供待格式化的信息。
下面的代码块中有两个格式化变量的例子:
yes_votes = 42_572_654
total_votes = 85_705_149
percentage = yes_votes / total_votes
'{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
# ' 42572654 YES votes 49.67%'
请注意Notice how the yes_votes
填充了空格并且只为负数添加了负号。
这个例子还打印了 percentage
乘以 100 的结果,保留 2 个数位并带有一个百分号 (请参阅 格式规格迷你语言 了解详情)。
最后,还可以用字符串切片和合并操作完成字符串处理操作,创建任何排版布局。字符串类型还支持将字符串按给定列宽进行填充,这些方法也很有用。
列表数据类型支持很多方法,列表对象的所有方法所示如下:
list.append(x)
list.extend(iterable)
通过添加来自 iterable
的所有项来扩展列表。list.insert(i, x)
list.remove(x)
list.pop([i])
list.clear()
list.index(x[, start[, end]])
list.count(x)
list.sort(*, key=None, reverse=False)
就地排序列表中的元素list.reverse()
list.copy()
返回列表的浅拷贝。类似于 a[:]
。The simplest way to describe a function is with a function type expression.
These types are syntactically similar to arrow functions:
function (: (: string) => void) {
('Hello World')
}
function (: string) {
.()
}
()
Imagine we have a function called padLeft
.
function (: number | string, : string): string {
throw new ('Not implemented yet!')
}
string
, number
, and boolean
JavaScript has three very commonly used primitives: string
, number
, and boolean
.
number
: JavaScript does not have a special runtime value for integers, so there’s no equivalent to int or float - everything is simply number
<script setup>
当使用 <script setup>
时,defineProps()
宏函数支持从它的参数中推导类型:
<script setup lang="ts">
const props = defineProps({
foo: {
type: String,
required: true,
},
bar: Number,
})
props.foo // string
props.bar // number | undefined
</script>
Vue 本身就是用 TypeScript 编写的,所有的 Vue 官方库都自带了类型声明文件,开箱即用。
通过 create-vue 搭建的项目包含了预先配置好的 tsconfig.json。其底层配置抽象于 @vue/tsconfig 包中。
手动配置 tsconfig.json 时,请留意以下选项:
compilerOptions.isolatedModules
应当设置为 true
,因为 Vite 使用 esbuild 来转译 TypeScript,并受限于单文件转译的限制。
如果你正在使用选项式 API,需要将 compilerOptions.strict
设置为 true
(或者至少开启 compilerOptions.noImplicitThis
,它是 strict
模式的一部分),才可以获得对组件选项中 this
的类型检查。否则 this
会被认为是 any
。
如果你在构建工具中配置了路径解析别名,例如 @/\*
这个别名被默认配置在了 create-vue
项目中,你需要通过 compilerOptions.paths
选项为 TypeScript 再配置一遍。