As we all know, Python is a weakly typed language. In most cases, it is difficult to know the function parameter type or return value type. This may lead to forgetting what parameters the function needs to pass and what type of result is returned after a period of time, causing unnecessary trouble. The typing module can solve this problem very well.
The main functions of typing are:
As an additional explanation in the development document, it is convenient for users to understand the types of parameters passed in and returned when using it.
Type checking prevents inconsistencies in parameter and return value types during runtime. Adding modules will not affect the running of the program, and no formal errors will be reported. Pycharm supports typing and a yellow warning will appear when checking errors.
grammar:
def 函数名(参数名: 数据类型)-> 返回值类型:pass
变量名: 数据类型 = 变量值
Common label types:
Union: Union[X, Y] means that the variables (parameters) are either of type X or type Y.
Optional: Optional[X] is equivalent to Union[X, None], that is, it allows variables (parameters) to be None by default.
Tuple: Example: person: Tuple[str, int, float] = ('Mike', 22, 1.75), indicating that person is a tuple, and its internal element types are str, int, float respectively.
List: Example: var: List[int or float] = [2, 3.5], indicating that var is a list, and its internal elements can be of int or float type; var: List[List[int]] = [[1, 2] , [2, 3]], obviously just used in combination.
Dict: Example: dic: Dict[str, int], indicating that dic is a dictionary with keys of type str and values of type int.
Sequence: In some cases, it is not necessary to strictly distinguish whether a variable or parameter is a list type or a tuple type. In this case, a more general type can be used, called Sequence, whose usage is similar to List .
2. assert assertion
assert is usually used in code debugging to determine the correctness of the code that follows. If the condition is met (correct), the program will automatically execute backwards. If the condition is not met (error), the current program will be interrupted and generate An AssertionError.
Example:
a =-1assert a <0assert a >0
3. @property decorator and setter decorator
Examples and introduction:
Python provides @property装饰器、setter装饰器decorated methods that can be used as attributes
For example: Define a Examclass, in order to avoid directly _scoreoperating the internal properties, property装饰器、setter装饰器to achieve indirect control of the properties through the provided methods, which plays the role of encapsulation, hiding some properties that do not want to be exposed to the outside world, but only providing methods for users to operate. In the method, you can check the rationality of parameters, etc.
classExam(object):def__init__(self, score):
self._score = score
@propertydefscore(self):# 属性访问return self._score
@score.setterdefscore(self, val):# 属性赋值if val <0:
self._score =0elif val >100:
self._score =100else:
self._score = val
if __name__ =='__main__':
e = Exam(60)print(e.score)
e.score =90print(e.score)
e.score =200print(e.score)
4. *args and **kwargs
Both of them are variadic parameters in Python.
It is worth noting that argsthe sum kwargscan be modified at will, the focus is on *the sum **.
Function: Returns the description information of the object, used when the print function outputs.
Calling timing: print(对象) When using the print object, it will be called automatically.
Notice:
If the __str__() method is not defined, the reference address of the object is printed by default, which is the address of the storage space of the object variable in memory.
If the __str__() method is defined, what is printed is the return value of the method.
The __str__ method must return a string data.
Example:
classstr_test():def__init__(self, name):
self.name = name
def__str__(self):return'name:%s'%self.name
name = str_test('Tom')print(name)