Summary of python programming for novices

The role of Python global statement

When writing a program, if you want to **change (reassign)** a variable outside the function, and this variable will be used in many functions, you need to tell the Python program that the scope of this variable is global Variables, the global statement can define global variables.

Lambda anonymous function benefits

Streamline the code,lambda eliminate the need to define functions, map eliminate the need to writefor the loop process: a>

str_1 = ["中国", "美国", "法国", "", "", "英国"]
res = list(map(lambda x: "填充值" if x=="" else x, str_1))
print(res)  # ['中国', '美国', '法国', '填充值', '填充值', '英国']

Python error handling

Like other high-level languages, Python also has a built-in try...except...finally... error handling mechanism.

When we think that some code may go wrong, we can use try to run this code. If an execution error occurs, the subsequent code will not continue to execute, but will jump directly. Go to the error handling code, that is, the except statement block. After executing except, if there is a finally statement block, then implement. At this point, the execution is completed. Jump to error handling code,

Python built-in error types

  • IOError: Input and output abnormality
  • AttributeError: Attempt to access a property that an object does not have
  • ImportError: Unable to import modules or packages, basically a path problem
  • IndentationError: Syntax error, code is not properly aligned
  • IndexError: The subscript index exceeds the sequence boundary
  • KeyError: Trying to access a key that doesn't exist in your dictionary
  • SyntaxError: The logic syntax of the Python code is wrong and cannot be executed.
  • NameError: Use a variable that has not been assigned an object

Brief description of any() and all() methods

  • any(): True as long as one element in the iterator is true;
  • all(): The result is true only if all judgment items in the iterator return true.

What elements are false in Python?

Answer: (0, empty string, empty list, empty dictionary, empty tuple, None, False)

Methods to improve Python running efficiency

  1. Use generators because you can save a lot of memory;
  2. Loop code optimization to avoid excessive repetitive code execution;
  3. Core modules use Cython PyPy etc. to improve efficiency;
  4. Multi-process, multi-thread, coroutine;
  5. Multiple if elif For conditional judgment, the condition most likely to occur first can be written first, which can reduce the number of program judgments and improve efficiency.

Python singleton pattern

Why Python doesn’t provide function overloading

Refer to ZhihuWhy does Python not support function overloading? Are most other functions supported?

We know that 函数重载 is mainly to solve two problems.

  1. Variadic type.
  2. The number of variable parameters.

In addition, the basic design principle of a function overloading is that only when the functions of the two functions are exactly the same except for the parameter type and number of parameters, function overloading is used. If the functions of the two functions are actually different , then overloading should not be used, but a function with a different name should be used.

  1. For case 1, the function function is the same, but the parameter types are different. How does Python handle it? The answer is that there is no need to deal with it at all, because Python can accept any type of parameters. If the functions of the function are the same, then different parameter types are likely to be the same code in Python, and there is no need to make two different functions.
  2. For case 2, the function function is the same, but the number of parameters is different. How does Python handle it? As we all know, the answer isdefault parameters (default parameters). Setting those missing parameters as default parameters (default parameters) can solve the problem. Because you assume that the functions have the same function, those missing parameters will be needed after all. Therefore, since both case 1 and case 2 have solutions, Python naturally does not need function overloading.

Instance method/static method/class method

Python There are three methods in class syntax, instance method, static method, class method. Their differences are as follows:

  • Instance methods can only be called by instance objects, static methods (declared by @staticmethod decorator), class methods (declared by @classmethod decorator) ), can be called by a class or an instance object of a class;
  • 实例方法, the first parameter must be passed as an instance object by default, and self is generally used. 静态方法, there are no parameters required. 类方法, the first parameter must be passed to the class by default, generally used cls .

The example code is as follows:

class Foo(object):
    """类三种方法语法形式
    """
    def instance_method(self):
        print("是类{}的实例方法,只能被实例对象调用".format(Foo))

    @staticmethod
    def static_method():
        print("是静态方法")

    @classmethod
    def class_method(cls):
        print("是类方法")


foo = Foo()
foo.instance_method()
foo.static_method()
foo.class_method()
print('##############')
Foo.static_method()
Foo.class_method()

After the program is executed, the output is as follows:

is an instance method of class <class 'main.Foo'> and can only be called by instance objects< a i=3> is a static method is a class method ############## It is a static method It is a class method




The difference between __new__ and __init__ methods

  • __init__ method is not a constructor in the true sense, __new__ method is (the constructor of a class is a special member function of the class, it will Executed every time a new object of the class is created);
  • __new__The method is used to create an object and return the object. When the object is returned, the __init__ method will be automatically called for initialization. The __new__ method is better than < a i=3> method is executed earlier;__init__
  • __new__The method is a static method and the __init__ is an instance method .

Python function parameter passing

Refer to these two links, the one with the highest praise on stackoverflow explains it in detail
How do I pass a variable by reference?
Python interview questions

Personal summary (a little bad):

  • Pass mutable objects: list, dictionary, NumPy array ndarray and user-defined type (class) as parameters to the function. After changing it inside the function, the variable outside the function will also change (for Except for reassignment of variablesrebind the reference in the method)
  • Pass immutable objects: strings, tuples, and numbers as parameters to the function. After changing them inside the function, the variable outside the function will not change.

Python implements type checking for function parameters

Python's built-in functions generally check the function parameter types. Custom function parameter type checking can be implemented using the function isinstance(), for example:

def my_abs(x):
    """
    自定义的绝对值函数
    :param x: int or float
    :return: positive number, int or float
    """
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x > 0:
        return x
    else:
        return -x

After adding parameter checking, if the wrong parameter type is passed in, the function can throw an TypeError error.

Why is Python a dynamic language?

InPython, the equal sign= is an assignment statement. You can assign 任意数据类型 to a variable. The same variable Values ​​can be assigned repeatedly and can be variables of different types, for example:

a = 100 # a是int型变量
print(a)
a = 'ABC'  # a 是str型变量
print(a)

Pyhon The type of variable itself is not fixed, and variables of different types can be assigned repeatedly. It is called a dynamic language, and its counterpart is a static language. Static languages ​​must specify the variable type when defining variables. If the types do not match when assigning values, an error will be reported. Java/C++ are both static languages ​​(int a; a = 100)

Python decorator understanding

A decorator is essentially a Python function or class.It allows other functions or classes to add additional functionality without making any code modifications< a i=2>, the return value of the decorator is also a function/class object. It is often used in scenarios with cross-cutting requirements, such as: log insertion, performance testing, transaction processing, caching, permission verification, etc. Decorators are an excellent design to solve such problems. With decorators, we can extract a large amount of similar code that has nothing to do with the function itself into decorators and continue to reuse it. In a nutshell, the purpose of a decorator is to add additional functionality to an existing object.

Explanation of usage of map and reduce functions

1, map() The function receives two parameters, one is a function and the other is an Iterable. map will apply the passed function to the sequence in turn. Each element, and the result is returned as a new Iterator. The simple sample code is as follows:

# 示例1
def square(x):
    return x ** 2
r = map(square, [1, 2, 3, 4, 5, 6, 7])
squareed_list = list(r)
print(squareed_list)  # [1, 4, 9, 16, 25, 36, 49]
# 使用lambda匿名函数简化为一行代码
list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
# 示例2
list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) # ['1', '2', '3', '4', '5', '6', '7', '8', '9']

Note that the map function returns an Iterator (lazy sequence), which needs to be converted into a common list structure through the list function. As a high-order function, map() actually abstracts the operation rules.

2, reduce() The function also accepts two parameters, one is a function (two parameters), One is a sequence. The difference from map is that reduce continues the cumulative calculation of the result with the next element of the sequence. , the effect As follows:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

The sample code is as follows:

from functools import reduce
CHAR_TO_INT = {
    
    
    '0': 0,
    '1': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 9
}
def str2int(str):
    ints = map(lambda x:CHAR_TO_INT[x], str)  # str对象是Iterable对象
    return reduce(lambda x,y:10*x + y, ints)
print(str2int('0'))
print(str2int('12300'))
print(str2int('0012345'))  # 0012345

The difference between Python deep copy and shallow copy

Most objects in Python, such as listslist, dictionariesdict, setsset, numpy Arrays, and user-defined types (classes), are mutable. Meaning these objects or the values ​​they contain can be modified. But some objects are immutable, such as numeric int, string str and tuple tuple.

1. Copy immutable data types:

copies the immutable data type, regardless of copy or deepcopy, it is the same address. When the value of the shallow copy is an immutable object (numeric value, string, tuple), it is the same as the case of = "assignment", the object's id value is the same as the original value of the shallow copy.

2. Copy mutable data types:

  1. Direct assignment: It is actually a reference (alias) to the object.
  2. Shallow copy (copy): Copies the parent object and does not copy the child objects inside the object (copying can be understood as creating memory). The operations that generate shallow copies include the following:
    • Using slices [:] operations
    • Use a factory function (such aslist/dir/set). The factory function looks like a function, but is actually a class. When called, an instance of the type is actually generated, just like a factory. The goods are the same.
    • Use the functions in the copy module, , and < /span>. but their sub-objects still point to the unified object (reference) is an independent object, copy()b = a.copy()ab
  3. Deep copy (deepcopy): copy module’s deepcopy() method, completelyThe parent object and its child objects are copied, and the two are completely independent. Deep copy includes a copy of the sub-objects in the object, so changes to the original object will not cause changes to any sub-elements in the deep copy.

**Note: The difference between shallow copy and deep copy is only for composite objects. The so-called composite object (container) is an object that contains other objects, such as lists and class instances. For numbers, strings, and other "atomic" types (no sub-objects), there is no copy, and all that is generated are references to the original objects. **For a clearer and easier understanding, you can refer to thisarticle.

Looking at a sample program, you can understand the difference between shallow copy and deep copy:

#!/usr/bin/Python3
# -*-coding:utf-8 -*-

import copy
a = [1, 2, 3, ['a', 'b', 'c']]

b = a  # 赋值,传对象的引用
c = copy.copy(a)  # 浅拷贝
d = copy.deepcopy(a)  # 深拷贝

a.append(4)
a[3].append('d')

print(id(a), id(b), id(c), id(d))  # a 与 b 的内存地址相同
print('a = ', a)
print('b = ', b)
print('c = ', c)
print('d = ', d)  # [1, 2, 3, ['a', 'b', 'c']]

The program output is as follows:

2061915781832 2061915781832 2061932431304 2061932811400

a = [1, 2, 3, [‘a’, ‘b’, ‘c’, ‘d’], 4]
b = [1, 2, 3, [‘a’, ‘b’, ‘c’, ‘d’], 4]
c = [1, 2, 3, [‘a’, ‘b’, ‘c’, ‘d’]]
d = [1, 2, 3, [‘a’, ‘b’, ‘c’]]

Python inheritance polymorphism understanding

  • Polymorphism refers to performing the same operation on variables of different types, which will exhibit different behaviors depending on the type of object (or class).
  • Inheritance can get all the data and methods of the parent class. Subclasses can override the methods of the parent class or add their own unique methods.
  • First there is inheritance, then there is polymorphism. Objects of different classes will respond differently to the same message.

Python object-oriented principles

References

  1. Reference Hori
  2. 110 Python interview questions (real questions)
  3. Interview questions about Python
  4. Inheritance and polymorphism
  5. Python direct assignment, shallow copy and deep copy analysis

Guess you like

Origin blog.csdn.net/purple_love/article/details/134960296