Python Interview Guide

Source: Internet
Author: User

1. Basic Python syntax

1. @staticmethod and @classmethod

There are three methods in Python, instance methods, class methods (@classmethod), static methods (@staticmethod).

The first parameter of a class method is the CLS, which represents an instance of the class, and the static method is basically the same as a global function

Class A (object):
def foo (self, x):
Print ("Executing foo (%s,%s)"% (self, x))
Print (' Self: ', self)
@classmethod
Def class_foo (CLS, x):
Print ("Executing class_foo (%s,%s)"% (CLS, x))
Print (' CLS: ', CLS)
@staticmethod
def static_foo (x):
Print ("Executing Static_foo (%s)"% x)
A = A ()
Print (A.foo (1))
Print (A.class_foo (1))
Print (A.static_foo (1))
2, iterators and generators

Iterators: A way to access the elements of a collection, starting with the first element of the collection, until all the elements are accessed. The advantage is that you do not have to prepare all the elements in advance for the entire iteration, and only begin to calculate the element when you iterate to an element. Suitable for traversing a large collection. ITER (): The method returns the iterator itself, next(): The method is used to return the next element or data in a container.

Generator: A function with yield is no longer a normal function, but a generator. When the function is called, a generator object is returned. Unlike general functions that exit after generating a value, the generator function automatically suspends and pauses the execution state of the value after it has been generated.

' Iterator '
Print (' For x in ITER ([1, 2, 3, 4, 5]): ')
For x in ITER ([1, 2, 3, 4, 5]):
Print (x)

' Generator '
def myyield (n):
While n>0:
Print ("Start build ...:")
Yield n
Print ("Complete once ...:")
N-= 1
For I in Myyield (4):
Print ("traverse the resulting value:", i)
3. Closed Package

Closures can be implemented by passing a parameter to a function without immediate execution to achieve the purpose of deferred evaluation. The following three conditions are met: an inline function must be used, an inline function must refer to a variable in an external function, and an external function return value must be an inline function.

def delay_fun (x, y):
Def caculator ():
Return X+y
Return Caculator

Print (' Return a sum function, not sum ')
Msum = Delay_fun (3,4)
Print (' Call and sum: ')
Print (Msum ())
4, *args and **kwargs

These two are mutable parameters in Python that accept the passing of parameters. *args represents any number of nameless arguments, which are a tuple, **kwargs represents the keyword argument, and it is a dictionary. When using both *args and **kwargs, you must *args before **kwargs.

5. Duck Type:

In duck type, the focus is not on the type of object itself, but how he uses it. For example, in a language that does not use duck type, we can write a function that takes an object of type duck and invokes its method of walking and calling. In a duck-type language, such a function can accept an arbitrary type of object and invoke its method of walking and calling.

Class Duck ():
def walk (self):
Print (' I am duck,i can walk ... ')
def swim (self):
Print (' I am duck,i can swim ... ')
def call (self):
Print (' I am duck,i can call ... ')

Duck1=duck ()
Duck1.walk ()
# I AM Duck,i can walk ...
Duck1.call () # I AM Duck,i can call ...
6. @property and @setter

@property is responsible for turning a method into a property call. When operating on an instance, the interface is not exposed, but is implemented through getter and setter methods.

Class Student (object):
@property
DEF score (self):
Return Self._score

@score.setterdef score(self, value):    if not isinstance(value, int):        raise ValueError(‘score must be an intager‘)    if value<0 or value>100:        raise ValueError(‘score must between 0~100!‘)    self._score = value

s = Student ()
S.score = 60
Print (S.score)
S.score = 999
Print (S.score)
7. Multi-process and multi-threading

Process: is the smallest unit of resource allocation, and the cost of creation and destruction is large;

Thread: is the smallest unit of CPU scheduling, the cost is small, the switching speed is fast;

The operating system allocates CPU time slices to multiple threads, each of which is completed within the specified time slice. The operating system constantly switches from one thread to another, and on the macro side it is as if multiple threads were executing together.

Because of the presence of a global lock (Gil) in Python, only one thread that gets GIL at the same time is running, while the other threads are waiting, which results in multithreading just doing tick switching and not using multicore.

The difference between multi-threading and multi-process: (1) The same variable in a multi-process has one copy in each process, and (2) in multiple threads, all variables are shared by all threads, and any one variable can be modified by any one thread. The biggest danger of sharing data between threads is that multiple threads change a variable at the same time, altering the content.

From multiprocessing import Pool #多进程
From multiprocessing.dummpy import Pool #多线程
8. Class variables and instance variables

Ordinary variables (non-class variables), which are the variables that exist after being assigned. Class variables can be assigned by variable names outside of Def in class, and can be assigned through class objects in Def

Class Apple (object):
name = ' Apple '

P1 = Apple ()
P2 = Apple ()
P1.name = ' Orange '
Print (P1.name)
Print (P2.name)
9, the decorative device

An adorner is a factory function that takes a function as an argument and then returns a new function whose closure contains the decorated function. With adorners, it is possible to extract similar code in a number of functions unrelated to its own function (the @app.route used to define the route in flask, which is a good example), to achieve the purpose of code reuse. Can be applied to insert log, performance test, transaction processing and so on.

def deco (func):
def warpper (*args, **kwargs):
Print (' Start ')
Func (*args, **kwargs)
Print (' End ')
Return Warpper

@deco
def myfunc (parameter):
Print ("Run with%s"% parameter)

MyFunc ("Something")

Python Interview Guide

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.