[Introduction to Artificial Intelligence] Python standard library - typing (type annotation), assert assertion, @property decorator and setter decorator, *args and **kwargs, built-in method __str_ in Python classes

[Introduction to Artificial Intelligence] Python standard library - typing (type annotation), assert assertion, @property decorator and setter decorator, *args and **kwargs, built-in method __str__ in Python classes


1. Introduction to typing

  • 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:
  1. 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.
  2. 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 = -1
assert a < 0
assert a > 0

Insert image description here

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.
class Exam(object):
    def __init__(self, score):
        self._score = score
 
    @property
    def score(self): # 属性访问
        return self._score

    @score.setter
    def score(self, val): # 属性赋值
        if val < 0:
            self._score = 0
        elif val > 100:
            self._score = 100
        else:
            self._score = val
 
if __name__ == '__main__':
	e = Exam(60)
	print(e.score)
 
	e.score = 90
	print(e.score)
 
	e.score = 200
	print(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 **.
  • *args : 在传入的参数个数未知,且不需要知道参数名称时使用,它将参数保存成一个元组,元组名为args 。
  • **kwargs : 在传入参数个数未知,但需要知道参数的名称时使用,它将数据保存成一个字典,字典名为kwargs 。
  • Example:
def args_test(data1, *args, **kwargs):
    print('data1: ',data1)
    print('args:', args)
    print('type_of_args: ', type(args))
    print('kwargs: ' , kwargs)
    print('type_of_kwargs:' ,type(kwargs))
    
args_test(1,2,3,4,5,k1=6,k2=7,k3=8)

Insert image description here

5. Built-in method __str__ in Python class

  • 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:
  1. 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.
  2. If the __str__() method is defined, what is printed is the return value of the method.
  3. The __str__ method must return a string data.
  • Example:
class str_test():
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return 'name:%s'%self.name

name = str_test('Tom')
print(name)

Insert image description here

Guess you like

Origin blog.csdn.net/qq_44928822/article/details/131290633