Python interview collection

Posted by haddydaddy on Mon, 10 Jan 2022 21:37:12 +0100

python interview collection

preface

This is a python interview essence analysis, from basic to advanced.

1, python Basics (difficulty: ⭐ ️)

  1. Object type of python
    Immutable object types: int, float, decimal, complex, bool, str, tuple, range, frozenset, bytes
    Mutable object types: list, dict, set, bytearray, user defined, classes (unless specifically made immutable)

  2. variable
    Variables in Python are pointers. Because variables are pointers, all variables have no type restrictions and can point to any object. The memory space size of the pointer is independent of the type. Its memory space only stores the memory address of the data pointed to.
    All variables in Python are actually pointers to objects in memory. All variables are!

In addition, objects are divided into two categories: one is modifiable and the other is not modifiable. A mutable type is called a value type, and an immutable type is called a reference type.

  1. object
    Object = determine memory space + value stored in this memory space.

In Java, objects are allocated on the heap to store real data, while references open up memory space in the stack to reference an object (variables of value type are also stored on the stack).

  1. Value type (immutable object)
    In Python, numeric values (integer, floating-point), Boolean, String and tuple belong to value types and are not allowed to be modified (immutable types). The modification of numeric values actually makes the variable point to a new object (newly created object), so the problem of shared memory will not occur. This approach is the same as Java's immutable object (String) implementation. The original object is recycled by Python's GC.

  2. Reference type (variable type)
    In Python, lists, collections, and dictionaries are reference types. They themselves allow modification (variable types) to modify the value of the reference type. Because the addresses are the same, they will be modified.
    Two operations of a = [1, 2, 3] are performed, and the address values referenced by a are different, that is, two different objects are created, which is obviously different from the immutable data type. Therefore, for the variable data type, objects with the same value are different objects, that is, multiple objects with the same value are saved in memory, and the address values are different.
    The operation on a does not change the address value referenced by A. The change of value will not cause the new object, that is, the address will not change, but the content in the address has changed or the address has been expanded.
    Immutable exception: the "value" of an immutable object cannot be changed, but its constituent object can be changed.
    The main reason is that variables (that is, memory addresses) are stored in tuples. Therefore, when the object pointed to by the variable changes, if the variable changes (i.e. immutable type), the tuple ensures that the immutable type cannot be modified. If the variable pointing to the object changes and the variable does not change (i.e. variable type), the variable type stored in the tuple can be modified (because the variable itself does not change).

  3. summary
    The immutable data type in python does not allow the value of the variable to change. If the value of the variable is changed, it is equivalent to creating an object. For objects with the same value, there is only one object in memory, and there will be a reference count to record how many variables reference this object;

Variable data types allow variable values to change. That is, if you perform append, + = and other operations on a variable, you only change the value of the variable without creating an object, and the address of the object referenced by the variable will not change. However, for different objects with the same value, there will be different objects in memory, that is, each object has its own address, It is equivalent to saving multiple copies of objects with the same value in memory. There is no reference count here. It is a real object.
7. Parameter transfer
All Python objects are references, so the so-called value types are immutable types. Therefore, parameter passing in Python is to pass references, that is, to pass memory addresses. But for immutable types, passing references is no different from passing values. For mutable types, passing a reference is really passing the address of memory.
8. python only allows reference passing to facilitate memory management, because the memory recycling mechanism used by python is counter recycling.
9. Value transfer: it means to directly transfer the value of the variable and copy the value of the passed variable into the formal parameter, so that the internal operation of the function will not affect the external variable.

Reference passing: a reference is understood as the reference relationship between a variable (identifier) and data. The identifier points to a memory address through a reference. When you modify the content, you modify the content in the memory address pointed to by the identifier. Because the outside also points to the content in the memory, modification inside the function will affect the content outside the function.

In addition: list, dictionary and collection are container types and nested references.

2, Python advanced

1. Decorator (difficulty) ⭐ ️ ⭐ ️ ⭐ ️ ⭐ ️)

Use grammar sugar
The code is as follows (decorator without parameters):

def logger(func):
    def wrapper(*args,**kwargs):
        print("hello,i will run {} function:".format(func.__name__))
        func(*args,**kwargs)
    return wrapper

@logger
def add(a,b):
    print('{} + {} = {}'.format(a,b,a + b))
add(1,2)

The code is as follows (decorator with parameters):

def small_talk(language):
    def wrappe(func):
        def defin(*args,**kwargs):
            print("{}".format(func.__name__))
            if language == 'china':
                print("Hello")
            elif language == 'English':
                print('hello')
            else:
                print("I dont know")
            func(*args,**kwargs)
        return defin
    return wrappe
@small_talk("china")
def wang():
    print('say')
@small_talk("English")
def dawei():
    print('say')
wang()
dawei()

The code is as follows (class decorator without parameters):
Note: class based decorators must be implemented__ init__ And__ call__ Two built-in methods
__ init__ : Receive decorated function__ call__ : Realize decoration logic.

class logger(object):
    def __init__(self,func):
        self.func = func
    def __call__(self, *args, **kwargs):
        print("[INFO]: the function {func}() is running..." \
              .format(func=self.func.__name__))
        return self.func( *args, **kwargs)
@logger
def say(sth):
    print('say {}'.format(sth))

The code is as follows (class decorator with parameters):
Note:__ init__ : Instead of the modified function, the incoming parameter is now received__ call__ : Realize decoration logic.

class logger(object):
    def __init__(self,level = "INFO"):
        self.level = level
    def  __call__(self, func):
        def wrapper(*args,**kwargs):
            print("[{level}]:the fuction {func}() is running"\
                  .format(level = self.level,func = func.__name__))
            func(*args,**kwargs)
        return wrapper

@logger(level="WARing")
def report(info):
    print("{}".format(info))
report("wrong")

The code is as follows (built-in decorator: property):
A function decorated with @ property will define a function as a property, and the value of the property is the content of the function return.

class Student(object):
    def __init__(self, name):
        self.name = name
        self.name = None
    def set_age(self, age):
        if not isinstance(age, int):
            raise ValueError('Illegal entry: age must be a numeric value!')
        if not 0 < age < 100:
            raise ValueError('Illegal input: age range must be 0-100')
        self._age=age

    def get_age(self):
        return self._age

    def del_age(self):
        self._age = None
xiaoming = Student("Xiao Ming")
xiaoming.set_age(20)
xiaoming.del_age()

Topics: Python Interview