- What the Python global statement does
- Benefits of lambda anonymous functions
- Python error handling
- Python built-in error types
- Brief description of any() and all() methods
- What element is false in Python?
- Ways to Improve Python Running Efficiency
- Python singleton pattern
- Why doesn't Python provide function overloading
- instance method/static method/class method
- Difference between __new__ and __init__ methods
- Python function parameter passing
- Python implements type checking for function parameters
- Why Python is a dynamic language
- Python decorator comprehension
- Map and reduce function usage explanation
- The difference between Python deep copy and shallow copy
- Python inheritance polymorphic understanding
- Python object-oriented principles
- References
What the Python global statement does
When writing a program, if you want to **change (reassign)** a variable outside the function, and this variable will act in many functions, you need to tell the Python program that the scope of this variable is a global variable, and the statement can be global
implemented Define the role of global variables.
Benefits of lambda anonymous functions
Simplify the code, lambda
eliminating the need to define functions and map
write for
loops :
str_1 = ["中国", "美国", "法国", "", "", "英国"]
res = list(map(lambda x: "填充值" if x=="" else x, str_1))
print(res) # ['中国', '美国', '法国', '填充值', '填充值', '英国']
Python error handling
Like other high-level languages, Python
it also has a built-in try...except...finally...
error handling mechanism.
When we think that some code may go wrong, we can use it try
to run this code. If an error occurs, the subsequent code will not continue to execute, but will directly jump to the error handling code, that is, except
the statement block, execute except
After , if there is finally
a statement block, execute it. At this point, the execution is complete. jump to the error handling code,
Python built-in error types
IOError
: I/O exceptionAttributeError
: Attempt to access a property that an object does not haveImportError
: Unable to import modules or packages, basically a path problemIndentationError
: syntax error, code is not properly alignedIndexError
: subscript index out of sequence boundaryKeyError
: Attempt to access a key that does not exist in your dictionarySyntaxError
: Python code logic syntax error, cannot be executedNameError
: use a variable that has not been assigned an object
Brief description of any() and all() methods
any()
: True as long as there is an element in the iterator that is true;all()
: All the judgment items in the iterator return true, and the result is true.
What element is false in Python?
Answer: (0, empty string, empty list, empty dictionary, empty tuple, None, False)
Ways to Improve Python Running Efficiency
- Use generators, because it saves a lot of memory;
- Loop code optimization to avoid excessive repetitive code execution;
- The core module uses
Cython PyPy
etc. to improve efficiency; - Multi-process, multi-thread, coroutine;
- For multiple
if elif
conditional judgments, the most likely condition to occur first can be written in front, which can reduce the number of program judgments and improve efficiency.
Python singleton pattern
Why doesn't Python provide function overloading
Reference Know why Python does not support function overloading? Most of the other functions are supported?
We know that it is 函数重载
mainly to solve two problems.
- Variadic type.
- Variable number of parameters.
In addition, the basic design principle of a function overloading is to use function overloading only when the functions of the two functions are exactly the same except for the parameter type and number of parameters. 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.
- For case 1, the function functions are 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 parameter, if the function of the function is the same, then different parameter types are likely to be the same code in Python, there is no need to make two different functions. - For case 2, the function functions are the same, but the number of parameters is different, how does Python handle it? As you know, the answer is default parameters (default parameters) . The problem can be solved by setting those missing parameters as default parameters (default parameters). Since you're assuming that the functions do the same, those missing parameters are needed after all. So, 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 methods, static methods, and class methods . Their differences are as follows:
- Instance methods can only be called by instance objects, static methods (declared by
@staticmethod
decorators ), class methods (@classmethod
declared by decorators), can be called by classes or instance objects of classes; 实例方法
, the first parameter must pass the instance object by default, and it is generally customary to use self.静态方法
, the parameter is not required.类方法
, the first parameter must pass the class by default, which is generally usedcls
.
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:
It is an instance method of class <class ' main .Foo'> and can only be called by instance objects.
It is a static method
and a class method
###############
is a static method
and a class method
Difference between __new__ and __init__ methods
__init__
The method is not the real constructor,__new__
the method is (the constructor of the class is a special member function of the class, which will be 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,__init__
the method for initialization,__new__
and the method is executed earlier than__init__
the method ;__new__
The method is a static method ,__init__
not an instance method .
Python function parameter passing
Refer to these two links, the most praised one on stackoverflow is very detailed
How do I pass a variable by reference?
Python interview questions
Personal summary (a bit bad):
- Pass variable objects: list list, dictionary dict, NumPy array ndarray, and user-defined types (classes) to the function as parameters. After the function is changed inside, the variable outside the function will also change (except for reassignment of the variable)
rebind 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
The built-in functions generally check the function parameter type, and the custom function parameter type check can isinstance()
be implemented , 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
With parameter checking added, functions can throw an TypeError
error .
Why Python is a dynamic language
Python
In , the equal sign =
is an assignment statement, which can be 任意数据类型
assigned to a variable, and the same variable can be assigned repeatedly, and it can be different types of variables, for example:
a = 100 # a是int型变量
print(a)
a = 'ABC' # a 是str型变量
print(a)
The type of variable itself in Python 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 language must specify the variable type when defining a variable. If the type does not match when assigning a value, an error will be reported. Java/C++ are both static languages ( int a; a = 100
)
Python decorator comprehension
A decorator is essentially a Python function or class, which allows other functions or classes to add additional functions without any code modification . The return value of the decorator is also a function/class object. It is often used in scenarios with cross-cutting requirements, such as: inserting logs, performance testing, transaction processing, caching, permission verification and other scenarios. Decorators are an excellent design to solve such problems. With decorators, we can extract a large amount of identical code that has nothing to do with the function itself into the decorator and continue to reuse it . In a nutshell, the role of a decorator is to add additional functionality to an existing object .
Map and reduce function usage explanation
1. map()
The function receives two parameters, one is a function and the other is an Iterable. map applies the incoming function to each element of the sequence in turn, and returns the result 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 ), and the other is a sequence. map
The difference from reduce is that the result will continue to be accumulated with the next element of the sequence . The effect is 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 lists
list
, dictionariesdict
, setsset
,numpy
arrays, and user-defined types (classes), are mutable. means that these objects or contained values can be modified. But there are also some objects that are immutable, such as numbersint
, stringsstr
, and tuplestuple
.
1. Copy immutable data types:
Copying immutable data types, regardless of copy
or deepcopy
, is the same address. When the value of the shallow copy is an immutable object (number, string, tuple), as in the case of = "assignment", id
the value shallow copy.
2. Copy variable data types:
- Direct assignment: In fact, it is a reference (alias) to an object.
- Shallow copy (
copy
): copy the parent object, and will not copy the child objects inside the object (copy can be understood as creating memory). The operations that produce shallow copies are as follows:- Use the slice
[:]
operation - Using a factory function (such as
list/dir/set
), the factory function looks like a function, but is actually a class, and when called, it actually generates an instance of the type, just like the factory produces goods. - Using the functions
copy
in the module , , and are separate objects, but their subobjects still point to the same object (references) .copy()
b = a.copy()
a
b
- Use the slice
- Deep copy (
deepcopy
):deepcopy()
The method completely copies the parent object and its child objects, and the two are completely independent. A deep copy contains 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 objects (containers) are objects that contain other objects, such as lists and class instances. For numbers, strings, and other "atomic" types (no sub-objects), there is no such thing as copying, and all references to the original object are generated. **For a clearer and easier to understand understanding, you can refer to this article .
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 polymorphic understanding
- Polymorphism refers to performing the same operation on variables of different types, and it will exhibit different behaviors depending on the type of object (or class).
- Inheritance can get all the data and methods of the parent class, and the subclass can rewrite the methods of the parent class, or add its own unique methods.
- There is inheritance first, and then polymorphism. Objects of different classes will respond differently to the same message.
Python object-oriented principles
- Python Craftsman: Principles of Writing Object-Oriented Code (Part 1)
- Python Craftsman: Principles of Writing Object-Oriented Code (Part 2)
- Python Craftsman: Principles of Writing Object-Oriented Code (Part 2)