# 函数定义中的星号和反斜杠号

在阅读源码时, 经常会遇到一些函数的定义中有`*`, `/`, `[]`这些特殊符号. 其中中括号作为上面三种中最常见的一种, 左右中括号之间的变量在调用函数时, 可以给可不给.

但`*`和`/`符号见的比较少.

## 型参列表中`*`的作用

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

也就是说调用该函数时, 给`*`后面定义的参数传参时, 只能用关键字字典的格式传, 而不能寄希望于按顺序给定并分配.

```python
>>> def func(a, *, b):
...     print(a, b)
... 
>>> func(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() takes 1 positional argument but 2 were given
>>> func(1, b=2)
1 2
>>>
```

## 型参列表中`/`的作用

`/`前的参数只能是位置参数, 不能是关键字参数. 例如`sum`函数的定义如下:

```python
def sum(iterable, start=0, /)
```

采用如下的方式调用会报错:

```python
sum([1], start=0)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-02aa4e519b31> in <module>()
----> 1 sum([1], start=0)

TypeError: sum() takes no keyword arguments
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kerasnoone.gitbook.io/garnet/gong-cheng-zhan/python/built-in/han-shu-ding-yi-zhong-de-xing-hao-he-fan-xie-gang-hao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
