Article directory
1. Code hints in Python
1. PyCharm function name prompt function
Create a data variable and assign it a list container type object,
When calling the clear function of data, input the cl type, the name of the clear method will be automatically prompted, and the code can be automatically completed;
If in a function, a variable of type list is received, the variable in our mind is a list container type, but the type of the variable is not marked, at this time, if we want to call its clear function, there is no prompt;
Of course, the call will not report an error;
2. PyCharm function parameter type prompt function
In Python, use the official function library, such as random number function,
"""
类型注解 代码示例
"""
import random
random.randint()
Move the mouse to the random.randint() function, press Ctrl + P shortcut key, you can see the parameter type prompt;
Define an add function by yourself, move the mouse to the function brackets, and use the shortcut key of Ctrl + P, and the parameter type hint cannot be given;
This is because PyCharm cannot determine what type of parameter should be passed in the add function through the code;
2. Type annotations
1. Introduction to the concept of type annotation
"Type annotation" in Python is to explicitly specify the type of variable/function parameter/return value in the code;
"Type annotations" can allow other programmers in the team to better read/understand/maintain this code. For the PyCharm integrated development environment, it can provide better code hints/code auto-completion functions based on type annotations;
Python 3.5 or above, supports "type annotation" syntax, specifying the type of variable and method parameter return value;
Python type annotation syntax is similar to type declaration in Kotlin syntax;
Type annotations can facilitate static type checking tools, type checking and code automatic prompting functions of PyCharm IDE development tools;
2. Type annotation syntax
Python type annotation syntax: After the variable/parameter, add a colon first, then add the variable/parameter type after the colon, and separate multiple variables/parameters with commas;
变量名/参数名 : 类型名称
Type annotations are not mandatory, but are used to improve code readability and maintainability;
During development, static type checking tools can be used to check whether the type annotations are correct;
Code Example - Python Type Annotations: In the code below,
- The variable a is designated as an int type, and its initial value is set to 10;
- The formal parameter types of x and y are specified as int type, and the return value type is also specified as int type;
a: int = 10
def add_numbers(x: int, y: int) -> int:
return x + y