Home >Backend Development >Python Tutorial >60 Python interview questions & answers selected! A must read when looking for a job after the new year
The latest 60 Python interview questions & answers in 2019! A must-read when looking for a job in the new year, benefits for Pythons. [Recommended tutorial: Python tutorial]
1. What are the characteristics and advantages of Python?
Answer: Omitted.
2. What is lambda function? What are its benefits?
A lambda function is a function that can accept any number of parameters (including optional parameters) and return a single expression value. Lambda functions cannot contain commands, and they cannot contain more than one expression. Don't try to cram too much into a lambda function; if you need something more complex, define a normal function and make it as long as you want.
The lambda function can accept any number of parameters, including optional parameters, but there is 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
You can also use the lambda function directly without assigning it to a variable:
>>> (lambdax,y=0,z=0:x y z) (3,5,6)
14
If your function is very simple, with only one expression and no commands, consider the lambda function. Otherwise, you'd better define a function. After all, functions don't have so many restrictions.
3. What is the difference between deep copy and shallow copy?
Deep copy is to copy the object itself to another object. This means that if you make changes to a copy of an object, the original object will not be affected. In Python, we use the deepcopy() function to perform deep copy. The usage method is as follows:
>>> import copy
>>> b=copy.deepcopy( a)
Shallow copy is to copy the reference of an object to another object. So if we make changes in the copy, it will affect the original object. Use the copy() function to perform a shallow copy. The usage method is as follows:
>>> b=copy.copy(a)
4. What are the differences between lists and tuples? different?
try…except…except…[else…][finally…]
Execute the statement under try. If an exception is thrown, the execution process will jump to the except statement. Try to execute each except branch sequentially. If the exception raised matches the exception group in except, execute the corresponding statement. If all excepts do not match, the exception will be passed to the next highest-level try code that calls this code.
The statement under try is executed normally, and the else block code is executed. If an exception occurs, it will not be executed; if there is a finally statement, it will always be executed in the end.
5. How to generate random numbers in Python?
Answer: random module
Random integer: random.randint(a,b): Returns a random integer x, a<=x<=b
random. randrange(start,stop,[,step]): Returns a random integer range between (start,stop,step), excluding the end value.
Random real number: random.random(): Returns a floating point number between 0 and 1
random.uniform(a,b): Returns a floating point number within the specified range
6. How to implement multi-threading in Python?
a. Python has a multi-threading package, but if you want multi-thread to speed up your code, it is usually not a good idea to use it.
b. Python has a structure called GlobalInterpreter Lock (GIL). The GIL ensures that only one "thread" can execute at any time. One thread gets the GIL, does a little work, and then passes the GIL to the next thread.
c. This happens very quickly, so to the human eye it appears that your threads are executing in parallel, but they are actually just taking turns using the same CPU core.
d. All these GIL passes add execution overhead. This means that if you want your code to run faster, it's generally not a good idea to use the threading package.
7. How to use the ternary operator in python?
The ternary operator is an operator used to display conditional statements. This contains statements that evaluate to a true or false value.
Syntax: The ternary operator syntax is as follows,
[on_true] if [expression] else [on_false]
Example:
x, y = 25,50
big = x if x < y else y
If x 8. Explain inheritance in Python with an example. Inheritance allows one class to obtain all members (such as properties and methods) of another class. Inheritance provides code reusability, making it easier to create and maintain applications. The class we inherit is called super-class and the class we inherit from is called derived/subclass. The following are the different types of inheritance supported by Python: a. Single inheritance - a derived class obtains members of a single superclass. b. Multi-level inheritance - Derived class d1 inherits from base class base1, and d2 inherits from base2. c. Hierarchical inheritance - any number of subclasses can be inherited from a base class d. Multiple inheritance - a derived class inherits from multiple base classes. 9. Explain what Flask is and its benefits? Flask is a Python web microframework based on the "Werkzeug, Jinja2 and Good Intentions" BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it has almost no dependencies on external libraries. It makes the framework lightweight with only few dependencies on updates and fewer security bugs. Sessions basically allow you to remember information from one request to another. In flask, sessions use signed cookies so that the user can view the session content and modify it. If and only if there is a key Flask.secret_key, the user can modify the session. 10. What is a dictionary in Python? The built-in data type in Python is called a dictionary. It defines the one-to-one relationship between keys and values. A dictionary contains a pair of keys and their corresponding values. Dictionaries are indexed by keys. Let’s take an example: The following example contains some keys, Country, Capital & PM, and their corresponding values are India, Delhi and Modi respectively. dict={'Country':'India','Capital':'Delhi','PM':'Modi'} print dict[Country] India print dict[Capital] Delhi print dict[PM] Modi 11. What is Negative exponents, why are they used? Sequences in Python are indexed and consist of positive and negative numbers. Positive numbers use '0' as the first index, '1' as the second index, and so on. Negative indexes start from '-1', which represents the last index in the sequence, '-2' as the second-to-last index, and so on. 12. How to query and replace a text string using Python? You can use the sub() method to query and replace. The format of the sub method is: a. sub(replacement, string[,count=0]) b. replacement is the text to be replaced c. string is the text to be replaced d. count is an optional parameter, referring to the maximum number of replacements 13. Explain Python’s and-or syntax is similar to the C expression bool ? a : b, but bool and a or b, when a is false, Doesn't work like the C expression bool ? a : b The and-or trick should be encapsulated into a function: defchoose(bool, a,b): return(booland[a ]or[b])[0] Because [a] is a non-empty list, it can never be false. Even if a is 0 or '' or some other false value, list[a] is true because it has one element. 14. Please write a piece of Python code to delete duplicate elements in a list 1, use the set function, set(list) 2. Use dictionary function, >>>a=[1,2,4,2,4,5,6,5,7,8,9,0] >>> b={} >>>b=b.fromkeys(a) >>>c=list(b.keys ()) >>> c 15. What is the difference between single quotation marks, double quotation marks and triple quotation marks? Single quotation marks and double quotation marks are equivalent. If you want to break a line, you need the symbol (\). Triple quotation marks can wrap the line directly and can contain comments. If you want to express Let's go this string Single quotation mark: s4 = 'Let\'s go' Double quotation mark: s5 = "Let's go" s6 = 'I really like" python"! ’ This is why both single quotes and double quotes can represent strings. 16. Are all memory allocations released when exiting Python? the answer is negative. Variables with object circular references or global namespace references are often not released when Python exits In addition, some contents retained by the C library will not be released. 17. What is the difference between search() and match() in Python? The match() function only detects whether RE matches at the beginning of the string. search() will scan the entire string to find a match. That is to say, match() will only match if it succeeds at position 0. Return, if the starting position is not matched successfully, match() returns none. 18. How to randomize items in a list in Python? Consider the example shown below: from random import shuffle x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High'] shuffle(x) print(x) The output of the following code is as follows. ['Flying', 'Keep', 'Blue', 'High', 'The','Flag'] 19. The process of compiling and linking in python What is it? Compilation and linking allows new extensions to be compiled correctly without any errors and can only be linked if they pass the compilation process. If dynamic loading is used, it depends on the system-provided styles. The Python interpreter can be used to provide dynamic loading of configuration settings files and the interpreter will be rebuilt. This requires the following steps: a. Create a file with any name and in any language supported by the system compiler. For example file.c or file.cpp b. Place this file in the Modules/ directory of the distribution you are using. c. Add a line in the Setup.local file that exists in the Modules/ directory. d. Run the file using spam file.o e. After successfully running this rebuild interpreter, use the make command in the top-level directory. f. If the file has changed, use the command "make Makefile" to run rebuildMakefile. 20. Python explains the split(), sub(), subn() methods of the "re" module. To modify strings, Python's "re" module provides 3 methods. They are: split() - "split" the given string into a list using regular expressions. sub() - Finds all substrings matching a regular expression pattern and replaces them with different strings subn() - It is similar to sub() and also returns New string and replacement sequence number. 21. What is the difference between range and xrange? For the most part, xrange and range are functionally identical in that they both provide a way to generate a list of integers for you to use. The only difference is that range returns a Python list object and xrange returns an xrange object. This means that xrange does not actually generate static lists like run-time. It creates values as needed using a special technique called yielding. This technique works with an object called a generator. This means that if you have a really huge range and you want to generate a list, say 1 billion, xrange is the function to use. This is especially true if you have a really memory-sensitive system, such as the phone you're using, because range will use as much memory as it does to create the integer array, which can cause memory errors and cause the program to crash. 22. Differences between Django, Pyramid and Flask. Flask is a "microframework" mainly used for small applications with simpler requirements. In Flask you have to use external libraries. Pyramid is suitable for large applications. It provides flexibility and allows developers to use the right tools for their projects. Developers can choose the database, URL structure, template style, etc. Django can also be used like Pyramid for larger applications. 23. List inherited styles in Django. In Django, there are three possible inheritance styles: Abstract base class: Use this when you just want the parent class to contain information that you don't want to type for each child model style. Multi-table inheritance: Use this style if you are sub-classing existing models and need each model to have its own database table. Proxy model: You can use this model if you only want to modify the Python level behavior of the model without changing the model's fields. 24. What is Python monkey patch? In Python, the term monkey patch refers only to the dynamic modification of a class or module at run-time. Consider the following example: # m.py class MyClass: def f(self): print "f ()" Then we can run the monkey-patch test like this: import m def monkey_f(self): print "monkey_f( )" m.MyClass.f = monkey_f obj = m.MyClass() obj.f() The output is as follows: monkey_f() We can see that outside the module, we did make some changes to the behavior of function f(), and the function monkey_f() is actually executed. 25. There are two sequences a and b, both of size n. The values of the sequence elements are arbitrary integer numbers, disordered? Requirement: By exchanging the elements in a and b, the difference between [the sum of the elements of sequence a] and [the sum of the elements of sequence b] is minimized. 1. Merge the two sequences into one sequence and sort them into the sequence Source 2. Take out the largest element Big and the second largest element Small 3. The remaining sequence S[:-2] is divided equally to obtain the sequence max, min 4. Add Small to the max sequence, increase Big to the min sequence, and recalculate the new sequence sum. The larger sum is max. , the small one is min. 26. How to send emails using Python? You can use the smtplib standard library. The following code can be executed on a server that supports SMTP listeners. import sys, smtplib fromaddr =raw_input("From: ") toaddrs = raw_input("To: "). split(',') print “Enter message, end with ^D:” msg = ” while 1: line = sys .stdin.readline() if not line: break msg = msg line # Send mail part server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg) server.quit() 27. Please write a Python logic to count the number of uppercase letters in a file. >>> import os >>>os.chdir('C:\\ Users\\lifei\\Desktop') >>> with open('Today.txt') astoday: count=0 for i in today.read(): if i.isupper(): count =1 print(count) Running result: 26 28. How long can an identifier be in Python? In Python, identifiers can be of any length. In addition, we must abide by the following rules when naming identifiers: a. It can only start with an underscore or a letter in A-Z/a-z b. The rest can use A-Z/a-z/ 0-9 c. Case sensitive d. Keywords cannot be used as identifiers. There are the following keywords in Python: 29. Explain Python The //, % and ** operators in //operator perform floor division (downward division), it will return the integer part of the integer division result. >>> 7//2 3 After divisibility here, 3.5 will be returned. Similarly, perform exponentiation operation. ab will return a raised to the power b. >>> 2**10 1024 Finally, % performs the modulo operation and returns the remainder of the division. >>> 13%7 6 >>> 3.5%1.5 0.5 30. How to use multi-base numbers in Python? In Python, in addition to decimal, we can also use binary, octal and hexadecimal. a. Binary numbers are composed of 0 and 1, and we use 0b or 0B prefix to represent binary numbers. >>> int (0b1010) 10 b. Use the bin() function to convert a number to its binary form. >>> bin (0xf) '0b1111' c. The octal number consists of numbers 0-7, and the prefix 0o or 0O is used to represent 8-base system number. >>> oct (8) '0o10' d. The hexadecimal number consists of numbers 0-15, represented by the prefix 0x or 0X Hexadecimal number. >>> hex(16) '0x10' >>> hex(15) '0xf' 31. How to get the list of all keys in the dictionary? Use keys() to get all keys in the dictionary >>>mydict={'a':1,'b':2,'c': 3,'e':5} >>> mydict.keys() dict_keys(['a', 'b', 'c', 'e'] ) 32. How to declare multiple variables and assign values? There are two ways: >>> a,b,c=3,4,5 #This assigns 3,4, and 5 to a, b, and c respectively >>> a=b=c=3 #This assigns 3 to a,b, and c 33. Decapsulation of tuples What is it? First let’s look at decapsulation: >>> mytuple=3,4,5 >>> mytuple (3, 4, 5) This encapsulates 3, 4, 5 into the tuple mytuple. Now we unpack these values into variables x, y, z: >>> x,y,z=mytuple >> ;> x y z Get results 12. 34. Explain how to set up a database in Django. You can use the command edit mysite/setting.py, which is an ordinary python module. The module level represents Django settings. Django uses SQLite by default; this is easy for Django users, so no other kind of installation is required. If your database selection is different, you must use the following keys in the DATABASE 'default' key to match your database connection settings. Engine: You can use 'django.db.backends.sqlite3', 'django.db.backeneds.mysql', 'django.db.backends.postgresql_psycopg2', 'django.db.backends.oracle' Wait to change the database Name: The name of the database. If you are using SQLite as your database, the database will be a file on your computer and Name should be the full absolute path, including the filename of the file. If you do not select SQLite as the database, you must add password, host, user and other settings. Django uses SQLite as the default database, which stores data as individual files in the file system. If you have a database server - PostgreSQL, MySQL, Oracle, MSSQL - and want to use it instead of SQLite, then use the database's management tool to create a new database for your Django project. Either way, with your (empty) database in place, all that's left is to tell Django how to use it. This is the source of the project's settings.py file. We will add the following lines of code to the file: DATABASES = { 'default': { 'ENGINE' : 'django.db.backends .sqlite3', 'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'), } } 35. How to get the Google cache time limit of any URL or web page? Use the following URL format: http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE Be sure to replace "URLGOESHERE" Give the correct web address for the page or site whose cache you want to retrieve, and check the time. For example, to view the Google Webcache age of edureka.co, you would use the following URL: http://webcache.googleusercontent.com/search?q=cache:edureka.co 36. What is the map function in Python? The Map function executes the function given as the first argument, which iterates over all elements of the iteration given as the second argument. If the given function contains more than 1 argument, many iterations are given. 37. How to get the index of the N largest values in a NumPy array? We can use the following code to get the index of the N largest values in a NumPy array: import numpy as np arr = np.array([1, 3, 2, 4, 5]) print(arr.argsort()[-3:][::-1]) output [ 4 3 1 ] 38. How do you calculate percentiles using Python/NumPy? We can calculate percentiles using the following code import numpy as np a = np.array([1,2,3,4, 5]) p = np.percentile(a, 50) #Returns 50th percentile, e.g. median print(p) Output 3 39. What are the advantages of NumPy arrays over (nested) Python lists? a. Python lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending and concatenation, and Python's list comprehensions make them easy to construct and manipulate. b. Some limitations of Python lists: they do not support "vectorized" operations such as element-wise addition and multiplication, and the fact that they can contain objects of different types means that Python must store each element's type information, and type dispatch code must be executed when operating on each element. c. NumPy is not only more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which can sometimes save you from unnecessary work. d. NumPy arrays are faster, you can use NumPy, FFT, convolution, fast search, basic statistics, linear algebra, histogram and other built-in methods. 40. What is the difference between NumPy and SciPy? a. In an ideal world, NumPy would only contain array data types and the most basic operations: indexing, sorting, reshaping, basic element functions, etc. b. All numerical code will reside in SciPy. However, an important goal of NumPy is compatibility, so NumPy attempts to retain all features supported by either of its predecessors. c. Therefore, NumPy contains some linear algebra functions, even though they belong more properly to SciPy. Regardless, SciPy contains more full-featured versions of its linear algebra modules, as well as many other numerical algorithms. d. If you use python for scientific computing, you should install NumPy and SciPy. Most new features belong to SciPy rather than NumPy. 41. How to solve the Chinese output problem of python program? Use encode and decode, such as: import os.path import xlrd,sys Filename='/home/tom/ Desktop/1234.xls' if not os.path.isfile(Filename): raise NameError,”%s is not a valid filename”%Filename bk =xlrd.open_workbook(Filename) shxrange=range(bk.nsheets) print shxrange for x in shxrange: p=bk. sheets()[x].name.encode('utf-8′) print p.decode('utf-8′) Method 2: In Add reload(sys) sys.setdefaultencoding('utf8′) 42. Read the following code and what is its output? ? class A (object): def go (self): print "go A go!" def stop (self ): print "stop A stop!" def pause(self): raise Exception("Not Implemented") class B( A): def go(self): super(B, self). go() print "go B go!" class C(A): def go(self): super(C, self). go() print "go C go!" def stop(self): super(C, self). stop() print "stop C stop!" class D(B,C): def go(self): super( D, self). go() print "go D go!" def stop(self): super(D, self). stop() print "stop D stop!" def pause(self): print "wait D wait!" class E( B,C): pass a = A() b = B() c = C() d = D() e = E() # Explain the output of the following code a.go() b.go() c.go() d.go() e.go() a.stop() b.stop( ) c.stop() d.stop() e.stop() a.pause() b.pause() c.pause() d.pause() e.pause() Answer, the output result is Comment form: a.go() # go A go! b.go() # go A go! # go B go! c.go() # go A go! # go C go! d .go() # go A go! # go C go! # go B go! # go D go! e.go() # go A go! # go C go! # go B go! a. stop() # stop A stop! b.stop() # stop A stop! c.stop() # stop A stop! # stop C stop! d.stop() # stop A stop! # stop C stop! # stop D stop! e.stop() # stop A stop! a.pause() # … Exception : Not Implemented b.pause() # … Exception: Not Implemented c.pause() # … Exception: Not Implemented d.pause() # wait D wait! e.pause() # …Exception: Not Implemented 43. Introduce the usage of webbrowser in Python? The webbrowser module provides a high-level interface to display Web-based documents. In most cases, only a simple call to the open() method is required. webbrowser defines the following exception: exception webbrowser.Error, this exception will be thrown when an error occurs in the browser control webbrowser has the following methods: webbrowser.open(url[, new=0[,autoraise=1]]) This method is to display the url in the default browser. If new = 0, then the url will be in the same Open under the browser window. If new = 1, a new window will be opened. If new = 2, a new tab will be opened. If autoraise = true, the window will automatically grow. webbrowser.open_new(url) Open a new window in the default browser to display the url, otherwise, open the url in the only browser window webbrowser.open_new_tab(url) Open a new tab in the default browser to display the url, otherwise it is the same as open_new() webbrowser.get([name]) Return a browser object based on name. If name is empty, return the default browser webbrowser.register(name, construtor[,instance]) Register a name as The browser of name, if this browser type is registered, can be obtained using the get() method. 44. In Python, what are the differences between list, tuple, dict, and set, and what scenarios are they mainly used in? Definition: list: linked list, ordered items, search by index, use square brackets "[]"; tuple: tuple, Tuples bring together various objects and cannot be modified. They are searched through indexes and use brackets "()"; dict: Dictionary. A dictionary is a combination of a set of keys and values. , search by key, no order, use curly brackets "{}"; set: set, unordered, elements only appear once, automatic deduplication, use "set ([])" ; Application scenarios: list, a simple data collection, you can use an index; tuple, use some data as a whole and cannot be modified; dict, data associated with keys and values; set, data only appears once, only cares about whether the data appears, not its location; Code: mylist = [1, 2, 3, 4, 'Oh'] mytuple = (1, 2, 'Hello', (4, 5)) mydict = { 'Wang' : 1, 'Hu' : 2, 'Liu' : 4} myset = set(['Wang', 'Hu', 'Liu', 4,'Wang']) 45. Write a function, input a string, and return the results in reverse order: such as: string_reverse('abcdef'), return: 'fedcba' (please use multiple methods to implement it, and review the implementation method Compare). Answer: Comparison of 5 methods. 1. The simple step size is -1, that is, the flipping of the string; 2. Exchange the positions of the front and rear letters; 3. Recursive method, each time Output a character; 4. Double-ended queue, use extendleft() function; 5. Use for loop, output from left to right; Code: string = 'abcdef' def string_reverse1(string): return string[::-1] def string_reverse2(string): t= list(string) l= len(t) for i,j in zip(range(l-1, 0, -1), range(l/ /2)): t[i], t[j] = t[j], t[i] return "".join(t) def string_reverse3(string): if len(string) <= 1: return string return string_reverse3(string[1:]) string[0] from collections import deque def string_reverse4(string): d= deque() d.extendleft(string) return ''.join(d) def string_reverse5(string): #return ''.join(string[len(string)-i] for i in range(1,len (string) 1)) return ''.join(string[i] for i in range(len(string)-1, -1, -1)) print(string_reverse1 (string)) print (string_reverse2 (string)) print (string_reverse3 (string)) print (string_reverse4 (string)) print (string_reverse5(string)) 46. Which of the following statements creates a dictionary? (Multiple correct answers possible) a) d = {} b) d = {"john": 40, "peter": 45} c)d = {40: "john", 45: "peter"} d)d = (40: "john", 45: "50") Answer: b, c, d. Create a dictionary by specifying keys and values. 47. Which one is the floor division? a) / b) // C) % d) No answers mentioned :b) //; For example, 5.0/2 = 2.5, 5.0//2 = 2 48. What is the maximum possible length of an identifier? a) 31 characters b) 63 characters c) 79 characters d) None of the above Answer: d) None of the above; identifiers can be of any length. 49. Why are local variable names starting with an underscore discouraged? a) They are used to represent private variables of a class b) They confuse interpreters c) They are used to represent global variables d) They slow down execution Answer: a) They are used to represent private variables of a class; since Python has no concept of private variables, leading underscores are used to represent variables that cannot be accessed from outside the class. 50. Which of the following is an invalid statement? a) abc = 1,000,000 b) a b c = 1000 2000 3000 c) a, b, c = 1000,2000,3000 d) a_b_c = 1,000,000 Answer: b) a b c = 1000 2000 3000; spaces are not allowed in variable names. 51. What is the output below? try: if '1' != 1: raise "someError" else: print ("someError has not occured") except "someError": print ("someError has occured") a)someError has occurred b) someError did not occur c) Invalid code d) None of the above Answer: c) Invalid code; new exception classes must inherit from BaseException. There is no such inheritance here. 52. Assume list1 is [2,33,222,14,25], what is list1 [-1]? a) Error b) No c) 25 d) 2 Answer: c) 25 ; Index -1 corresponds to the last index in the list. 53. To open the file c:\scores.txt for writing, we use: a) outfile = open("c:\scores.txt", "r") b) outfile = open ("c:\\scores.txt", "w") c) outfile = open (file = "c:\scores. txt", "r") d) outfile = open (file = "c:\\scores.txt", "o") Answer: b) This position contains a double slash The bar (\$$, w is used to indicate that the file is being written. 54. What is the output of the following? f = None for i in range (5): with open ("data.txt", "w") as f: if i > 2: break print f.closed a) True b) False c) None d) Error Answer: a) True; When used with an open file, the WITH statement ensures that the file object is closed when the with block exits. 55. When is the else part of try-except-else executed? a) Always b) When an exception occurs c) When no exception occurs d) When an exception occurs until except Block Answer: c) When no exception occurs; when no exception occurs, execute the else part. 56. a=1, b=2, do not use intermediate variables to exchange the values of a and b. Two forms: addition or XOR; code: a = 1 b = 2 a = a b b = a - b a = a - b print ('a = {0}, b = {1}'.format (a,b)) a = a ^ b b = a ^ b a = a ^ b print ('a = {0}, b = {1}'.format( a, b)) 57. Please write the print result x = [0, 1] i = 0 i, x[i] = 1, 2 print(x) Print result: [0, 2], python can use continuous assignment, from left to right. g = lambda x, y=2, z : x y**z g(1, z=10) = ? Print result: exception, formal parameter There can be default parameters only at the end of the table, and z needs to provide default parameters. 58. Python’s singleton pattern The singleton pattern is a commonly used software design pattern. It contains only one special class called a singleton class in its core structure. The singleton mode can ensure that there is only one instance of a class in the system and that the instance is easy to access from the outside world, thereby facilitating control of the number of instances and saving system resources. If you want only one object of a certain class to exist in the system, the singleton pattern is the best solution. __new__() is called before __init__() and is used to generate instance objects. Using the characteristics of this method and class attributes, the singleton pattern of the design pattern can be implemented. Singleton mode refers to creating a unique object. Classes designed in singleton mode can only be instantiated. This is definitely a common test. Definitely remember 1~2 methods. The interviewer asked you to write it by hand. Use __new__ method class Singleton (object): Shared attributes When creating an instance, point the __dict__ of all instances to the same dictionary, so that they have the same attributes and methods. class Borg(object): _state = {} def __new__(cls, *args, **kw): ob = super (Borg,cls). __new__(cls, *args, **kw) ob.__dict__ = cls._state return ob class MyClass2 (Borg): a = 1 Decorator version def singleton (cls): instances = {} def getinstance(*args, **kw): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return getinstance @singleton class MyClass: … import method As a python module, it is a natural singleton mode # mysingleton.py class My_Singleton(object): def foo(self): pass my_singleton = My_Singleton() # to use from mysingleton import my_singleton my_singleton.foo() 59. A and B are on two islands respectively. B is sick, and A has the medicine B needs. C has a boat and a lockable chest. C is willing to transport things between A and B, but the things can only be placed in boxes. As long as the box is unlocked, C will steal the contents of the box, no matter what is in the box. If A and B each have a lock and a key that can only open their own lock, how should A deliver things to B safely? Answer: A puts the medicine into the box and locks the box with his own lock. After B gets the box, he adds his own lock to the box. After the box is shipped back to A, A removes his own lock. When the box is delivered to B, B removes his own lock and obtains the medicine. 60. There are 25 horses with different speeds, but the speed of each horse is a fixed value. Now there are only 5 tracks and there is no way to time them. That means you can only know the relative speed of up to 5 horses in each race. What is the minimum number of races to find the top 3 fastest horses among the 25? Answer: Every horse must have at least one chance to compete, so 25 horses are divided into 5 groups. The first 5 games are inevitable. It will be easy to find the champion next. The champions of each group can play together for one game (Game 6). The last thing is to find the 2nd and 3rd places. We named the groups they were in in the first 5 games as A, B, C, D, and E according to the rankings obtained in the 6th game. That is: the champion of Group A is the first place in the 6th race, and the champion of Group B is the second place in the 6th race... The 5 horses in each group are numbered from fastest to slow according to their previous results: Group A: 1, 2, 3, 4, 5 Group B: 1, 2, 3, 4, 5 Group C: 1, 2, 3, 4, 5 Group D: 1, 2, 3, 4, 5 Group E: 1, 2, 3, 4, 5 What we got from now Information, we can know which horses have been excluded from the 3rd place. As long as it can be determined that 3 or more horses are faster than this horse, then it has been eliminated. It can be seen that only the 5 horses in bold blue in the above table may be ranked 2 or 3. That is: 2nd and 3rd place in Group A; 1st and 2nd place in Group B, and 1st place in Group C. Take these 5 horses for the 7th game. The top two in the 7th game will be the 2nd and 3rd place among the 25 horses. Therefore, there are at least 7 games in total. The above is the detailed content of 60 Python interview questions & answers selected! A must read when looking for a job after the new year. For more information, please follow other related articles on the PHP Chinese website!
def __new__ (cls, *args, **kw):
if not hasattr (cls, '_instance '):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kw)
return cls._instance
class MyClass(Singleton):
a = 1