Interview Stereotype-python

Because of the recent interview needs, I sorted out some stereotyped essays and referenced a lot

Interpreted and compiled languages

Compiled languages ​​require the use of a compiler to compile all source code into an executable program at one time, and one compilation can be executed repeatedly. Representative languages ​​include C, C++, Golang, assembly, etc.
An interpreted language uses an interpreter to convert while executing, and converts whatever source code is used, and does not generate an executable program. Representative languages ​​include JavaScript, Python, PHP, Shell, etc.

object-oriented and procedural-oriented

Process-oriented : refers to decomposing the problem into one step at a time, and each step is implemented with a function, which can be called in turn.
Object-oriented : decompose the transaction that constitutes the problem into various objects, and create an object to describe the behavior of a certain transaction in the steps of solving the problem; object-oriented characteristics: encapsulation, inheritance, polymorphism

Advantages of Python

  • Explanatory, easy-to-understand grammar and strong readability
  • There are many libraries available, allowing us to stand on the shoulders of giants to easily achieve the desired functions
  • Extensible, with connectable interfaces with other programming languages ​​or other software
  • Free open source, portable
  • Automatic memory management, allowing programmers to focus on code implementation

Python disadvantages

  • His interpretable features make it run slower
  • The characteristics of dynamic languages ​​may increase runtime errors.

decorator

A decorator is essentially a Python function that allows other functions to add additional functionality without any code changes. It accepts a function as a parameter and returns a function, using python's @ syntax to place

Functions : 1. Import log; 2. Function execution time statistics; 3. Preparatory processing before executing the function; 4. Cleanup function after executing the function; 5. Permission verification; 6. Cache

The difference and use of python decorator @staticmethod and @classmethod

Reason for use : Using @staticmethod or @classmethod, you can call directly class name. method name () without instantiation. This is good for organizing the code, putting some functions that should belong to a certain class into that class, and it is also good for the cleanliness of the namespace.

Difference between @staticmethod or @classmethod

  • Ordinary methods of the class, the first parameter requires the self parameter to represent itself.

  • @staticmethod does not need to represent the self of its own object and the cls parameter of its own class, just like using functions.

  • @classmethod also does not require a self parameter, but the first parameter needs to be a cls parameter representing its own class.

class Test(object):

    """docstring for Test"""

    def __init__(self, arg=None):

        super(Test, self).__init__()

        self.arg = arg

    def say_hi(self):

        print 'hello wrold'

    @staticmethod

    def say_bad():

        print 'say bad'

    @classmethod

    def say_good(cls):

        print 'say good'

def main():

    test = Test()

    test.say_hi()

    Test.say_bad() //直接类名.方法名()来调用

    Test.say_good() //直接类名.方法名()来调用

if __name__ == '__main__':

    main()

write a decorator

import time
def calc_time(func):
    def inner():
        t1 = time.time()
        func()
        t2 = time.time()
        print('cost time: {}s'.format(t2-t1))
    return inner

@calc_time
def test(x):
    for i in range(1000):
        print(x,end='')
    print('\n')
    return x

test(1) 

Deep Copy, Shallow Copy, and Equals Assignment

Deep copy : create a new object, copy the memory of the original object completely, and change the copied object without changing the content of the original memory. (the two objects are completely separate objects after copying)

Equal sign assignment : It is equivalent to marking a new label for the original object. Two references point to the same object. If one of them is modified, the other will also change.

Shallow copy : two cases, 1. When the value of the shallow copy is an immutable object (number, character, tuple), it is the same as the equal assignment, and the id value of the object is the same as the original value of the shallow copy; 2. If it is mutable Objects (lists, dictionaries, etc.), a. a simple object without nesting, the objects before and after copying will not affect each other, b. there are complex sub-objects in the object, such as list nesting, if you change the original object Values ​​of complex subobjects, values ​​of shallow copies are also affected, because only the references of the subobjects are copied (only the parent object is copied) during shallow copying.

How to implement multithreading in python

Thread , create a new thread, and then use GIL to implement thread communication

GIL

GIL (Global Interpretation Lock) can ensure that one thread is executed at a time. Threads save GIL in turn and perform some operations before passing him to the next thread, so that multiple processes can run on the CPU in turn, but this conversion is very fast, so that We feel that he is parallel.

How does Python memory manage

  • Reference counting : Python internally uses reference counting to keep track of objects in memory. Python internally records how many references the object has, that is, reference counting. When the object is created, a reference counting is created. When the object is no longer needed, When the reference count of this object reaches 0, it is garbage collected.

  • Garbage collection : Python checks objects with a reference count of 0 and clears the space they occupy in memory; circular reference objects are recycled with a circular garbage collector

  • Memory pool mechanism : In Python, most of the memory requested is a small block of memory, which will be released soon after the application. Since the application of these memory is not for creating objects, there is no object A first-level memory pool mechanism. This means that Python will perform a large number of malloc and free operations during runtime, and frequently switch between user mode and core mode, which will seriously affect the execution efficiency of Python. In order to speed up the execution efficiency of Python, Python introduces a memory pool mechanism to manage the application and release of small blocks of memory.

  • a) Python provides a garbage collection mechanism for memory, but it puts unused memory into the memory pool instead of returning it to the operating system.

  • b) All objects smaller than 256 bytes in Python use the allocator implemented by pymalloc, while large objects use the system's malloc. In addition, Python objects, such as integers, floating-point numbers, and Lists, have their own independent private memory pools, and objects do not share their memory pools. That is to say, if you allocate and release a large number of integers, the memory used to cache these integers can no longer be allocated to floating point numbers.

Python Garbage Collection Mechanism

(Automatically deal with the problem of allocating and reclaiming memory, and the hidden danger of memory leak is useless), mainly based on the reference counting mechanism, supplemented by two mechanisms: mark-clear and generational collection

The counting mechanism is that each object in python has a reference count value. When there is a reference, this value will increase. When the object referencing him is deleted, this value will decrease. When the reference count value is 0, the value When the life of the object ends, python will automatically reclaim this memory. (Disadvantage, circular reference, if l1 and l2 refer to each other, no other objects refer to them, these two pieces of memory can never be reclaimed)

Meaning of *args and **kwargs

Used to handle variable parameters. After receiving parameters, args will become a tuple, and kwargs will become a dict

Variadic means that the number of parameters is not known

When using *args and kwargs at the same time, the *args parameter must be listed before kwargs, otherwise an error will be reported.

def test(a,*args,**kwargs):
    print(a)
    print(args)
    print(kwargs)
test(1,3,5,7,c='2',d=4)
输出为:
1
(3, 5, 7)
{
    
    ‘c’:2, ‘d’: 4}

common method

join() and split()

  • join() , add the specified string to the string, or connect a list of strings followed by join with the specified string

  • split() , split the string with the specified characters, and the result is a list

strip(), lstrip(), rstrip()
remove spaces on both sides of the string

is family check string...
islower(), isupper(), istitle()...

isalnum(), isdigit(), isnumeric(), isdecimal()…

For
example, when a function has no idea how to write it, it can be used to occupy a place in the function to ensure that the grammar is correct.
Continue directly jumps to the next loop. Pass is a placeholder. Although nothing will happen, if the following statements are used, these statements will continue to run

yield

  • Save the current running state (breakpoint), and then suspend execution, that is, suspend the function

  • The value of the expression after the yeild keyword is returned as the return value. At this time, it can be understood that it plays the role of return. When the next() and send() functions are used to let the function continue to execute from the breakpoint, that is, the wake-up function.

match() and search()
match() detects whether the RE matches at the beginning of the string, and returns True only if the 0 match is successful, and search() scans the entire string to find a match

Modules and Packages

Module : contains and organized code snippets in python, xxx in xxx.py is the module name

Package : A hierarchical directory structure above modules that defines an application execution environment consisting of many modules or many subpackages. A package is a folder containing an __init__.py file and several module files.

Library : a collection of related functional modules, python has many standard libraries, third-party libraries...

Closure

Closures make it possible for local variables to be accessed outside a function.

python-operators(7)

Arithmetic, relational, assignment, logical, bit, member, identity operators

Multiple base numbers

0b binary (bin), 0o octal, 0x hexadecimal

Python standard data types (6)

  • Immutable data: 1.number (number type)
    2.string (string type)
    3.tuple (tuple type)

  • Variable data: 1.set (collection type)
    2.dictionary (dictionary type) (key, walue)
    3.list (list type)

tuple

tuple1=("hello",2,True)

Tuple uses parentheses ( ) to contain each data item. The
only difference between tuple and list is that the elements of tuple cannot be modified, while the elements of list can be modified

set (collection)

set1={
    
    1,2,3,"nihao","hello",1,2}
set2=set("hello word")

set is a sequence of unordered and non-repeating elements
Use curly braces { } or the set() function to create a collection
Use set() to create an empty collection
Use set to deduplicate

What is the PYTHONPATH variable

An environment variable in Python that is used to search paths when importing modules. Therefore it must contain the Python source library directory as well as the directory containing the Python source code.

Generator generator and iterator iterator

reference

Builder

A generator is a special kind of iterator. Generate a series of values ​​for iteration, continuously calculate the next element in the process of the for loop and end the loop under appropriate conditions

The function using yield returns an iterator

iterator

An iterator is a way to access collection elements. Its objects are accessed from the first element of the collection until all elements have been visited. Use iter() to create an iterator and call the next() function to obtain objects (iteration only can go forward but not backward).

The difference between the two:

  • Create/generate, the generator creates a function, generates/returns the object with the keyword yield; the iterator uses the built-in functions iter() and next()

  • The number of yield statements in the generator can be defined at the time of use, and the iterator cannot exceed the number of objects

  • When the generator yield suspends the loop, the generator will save the state of the local variable; the iterator will not use the local variable, saving more memory

Generators and functions:

The main difference between a generator and a function is that the function returns a value, and the generator yields a value while marking or remembering the point of the yield so that it can resume execution from the marked point when it is called next time. yield turns a function into a generator, which in turn returns an iterator.

Parameter passing mechanism

If the data type of the actual parameter is a mutable object (list, dictionary), the function parameter will be passed by reference. If they are immutable, such as strings, numbers, and tuples, they are passed by value.

Basic elements of Python objects (3), id, type and value

== compare value, that is, value, is compare id

Difference between __new__ and __init__

new : Called when an object is created, an instance of the current object will be returned

init : Called after the object is created, initialize some instances of the current object, no return value

Call sequence: first call __new__ to generate an instance and then call the __init__ method to initialize the instance, such as adding attributes.

List 5 python standard libraries

os : Provides many functions associated with the operating system

sys : usually used for command line arguments

re : regular match

math : mathematical operations

datetime : handle datetime

Dictionaries sorted by key from smallest to largest

y = {
    
    1:3, 2:2, 3:1}
by_key =  sorted(y.items(),key = lambda item:item[0])
by_value = sorted(y.items(),key = lambda item:item[1])
print (by_key)   #结果为[(1, 3), (2, 2), (3, 1)],即按照键名排列
print (by_value) #结果为[(3, 1), (2, 2), (1, 3)],即按照键值排列

Guess you like

Origin blog.csdn.net/weixin_44200259/article/details/128039399