Spring Python trick you must master the classic face questions

1: Python how to implement singleton pattern?
Python There are two ways to achieve single-mode embodiment, the following example uses two different ways Singleton:
1 / with the class

class Singleton(type): 
    def __init__(cls, name, bases, dict): 
        super(Singleton, cls).__init__(name, bases, dict)         
        cls.instance = None  
    def __call__(cls, *args, **kw):        
    	 if cls.instance is None: 
            cls.instance = super(Singleton, cls).__call__(*args, **kw)         
            return cls.instance   
class MyClass(object): 
    __metaclass__ = Singleton  
print(MyClass()) 

2 / decorator to use single-mode embodiment

def singleton(cls):     
	instance = {}   
def getinstance(): 
    if cls not in instances:       
    instances[cls] = cls()         
    return instances[cls]     
return getinstance()  
@singleton 
class MyClass:     
	pass

2: What is a lambda function?
Python allows you to define a single row of small functions. Lambda functions defined in the following form: labmda parameters: lambda expression is a default value function expression. You can also assign it to a variable. lambda function can accept any number of parameters, including the optional parameters, but only one expression:

 >>> g = lambda x, y: x * y >>> g(3, 4) 12 
>>> g = lambda x, y=0, z=0: x + y + z >>> g(1) 1 
>>> g(3, 4, 7) 14 

Lambda functions can also be used directly, without assigning it to a variable:


print((lambda x, y=0, z=0: x + y + z)(3, 5, 6)) 
14 

If your function is very simple, there is only one expression that does not contain a command, you can consider lambda functions. Otherwise, you still defined functions fishes, after all, not so much a function of restrictions.

3: Python is how to type conversion?
Providing Python or variable values are converted from one type to another type of built-in functions. int mathematical functions can be converted to meet the format numeric strings to integers. Otherwise, it returns an error message.

>>> int(34) 34 
>>> int(1234ab) #不能转换成整数 
ValueError: invalid literal for int(): 1234ab 
函数int也能够把浮点数转换成整数,但浮点数的小数部分被截去。
>>> int(34.1234) 34 
>>> int(-2.46) -2 
函数float将整数和字符串转换成浮点数: 
>>> float(12ʺ) 12.0 
>>> float(1.111111ʺ) 1.111111 
函数str将数字转换成字符: 
>>> str(98)98ʹ 
>>> str(76.765ʺ)76.765ʹ 

1 1.0 integer and floating point numbers are different in python. Although their values ​​are equal, but of a different type. This is not the same two numbers stored in the form of a computer.

4: Python how to define a function
function is defined in the form below:
DEF (arg1, arg2, ... argN):
function name must begin with a letter, you can include underscore "", but not the name Python keywords defined function . The number of statements within functions is arbitrary, each statement has at least one space indentation to indicate that this statement is part of this function. Indent the end of the place, the natural end of the function.

The following defines a function of the sum of two numbers:

def add(p1, p2): 
	print p1,+, p2,=, p1+p2 
add(1, 2) 
#1 + 2 = 3 

Objective function is to hide some complex operations, to simplify the structure of the program, making it easy
to read. Function before calling must be defined. Can only be executed if the external function call inside a function defined functions, internal functions. When the program calls a function, a function internal to the implementation of the internal function statement after the function completes and returns to where it left off the program, the next statement execution of the program.

5: Python is how memory management?
Python's memory management by the Python interpreter was responsible, developers can liberate out from the memory management affairs, committed to the development of the application, so that makes program development with fewer errors, more robust procedures, shorter development cycles

6: How to iterate over a sequence in reverse order? how do I iterate over a sequence in
reverse order if it is a list, the quickest solution is:

list.reverse() 
try: 
     for x in list:         
     pass 
finally: 
    list.reverse() 

If not the list, the most common but slightly slower solution is:

 for i in range(len(sequence) - 1, -1, -1):    
 	 x = sequence[i]    
    #   

7: How to implement in Python tuple and list of conversion?
Function tuple (seq) can all iterations (Iterable) sequence into a tuple, the same element, ordering does not change.

For example, tuple ([l, 2,3]) return (1,2,3), tuple ( 'abc') return ( 'a'. 'B', 'c'). If the argument is a tuple, then, copy function without any direct return to the original object, so when the object is not a tuple uncertain to call tuple () function is not very consuming.

Function list (seq) can convert all sequences and iterative objects into a list, and the same element, ordering does not change.
For example list ([1,2,3]) return (1,2,3), list ( 'abc ') return [ 'a', 'b' , 'c']. If the argument is a list, she would like the set [:] to make a copy of the same

. 8: Python is inscribed: Please write a piece of Python code for deleting the list of repetitive elements which
can be reordered first list, and then start scanning from the final list, the
code is as follows:

List = [1, 2, 1, 2, 1, 13, 3, 3, 4, 4, 2, 6, 7, 8, 8, 9] if List: 
    List.sort() 
    last = List[-1]     
    print(last, List) 
    for i in range(len(List) - 2, -1, -1):         # 从倒数第二个开始迭代,排除掉last         
    if last == List[i]:             
    	del List[i]         
    else: 
        last = List[i] 
print(List)  

9: Python file operation face questions

  1. How to delete a file using Python?
    Use os.remove (filename) or os.unlink (filename);
  2. How Python copy a file?
    shutil module has a file copy function can copyfile

10: How to generate random numbers in Python?

Standard random library implements a random number generator, the example code below: Import random
random_number = random.random () Print (random_number)
it returns a random floating point number between 0 and 1

Published 80 original articles · won praise 239 · Views 7069

Guess you like

Origin blog.csdn.net/weixin_37763870/article/details/104530355