Python Interview Guide (hi-talk)

Source: Internet
Author: User
Tags shallow copy

Selected 10 of the highest frequency of the topic, with the answer for your small partners reference!

What do 1.*args and **kwargs mean?

A: *args represents a mutable parameter (variadic arguments), which allows you to pass in 0 or any of the nameless parameters, which are automatically assembled as a tuple when the function is called, and the **kwargs represents the keyword argument (keyword arguments). It allows you to pass in 0 or any parameter with parameter names, which are automatically assembled into a dict inside the function. When using *args and **kwargs at the same time, it must be ensured that *args before **kwargs.

Extended reading:

53884455

2.python How to copy an object?

For:

(1) Assignment (=), is to create a new reference to the object, modify any one of the variables will affect the other;

(2) A shallow copy (Copy.copy ()), creates a new object, but it contains a reference to the containing item in the original object (if one object is modified by reference, the other is changed);

(3) deep copy (Copy.deepcopy ()), create a new object, and recursively copy the object it contains (modify one, and the other will not change)

Note: Not all objects can be copied

Extended reading:

Http://www.cnblogs.com/wilber2013/p/4645353.html

3. A brief description of Python's garbage collection mechanism

A: Garbage collection in Python is based on reference counting, which is supplemented by tag-purge and generational collection.

Reference count: Python stores a reference count for each object in memory, and if the count becomes 0, the object disappears and the memory allocated to the object is freed.

Tag-clear: Some container objects, such as list, dict, tuple, instance, and so on, may appear a reference loop, for which the garbage collector periodically recycles these loops (the objects are joined together by reference (pointers) to form a forward graph, and the object forms the node of the graph. , while the reference relationship forms the edge of the graph.

Generational collection: Python divides memory into three generations based on the object's survival time, and after the object is created, the garbage collector assigns the generation to which it belongs. Each object is assigned a generation, and the younger generation is prioritized, so the later objects are created more easily to be recycled.

Extended reading:

https://www.jianshu.com/p/1e375fb40506

4. What is a lambda function? What good is it?

A: lambda expressions, which are usually used when a function is needed, but do not want to be bothered to name a function, which means an anonymous function.

Python allows you to define a small single-line function. The lambda function is defined as follows (lambda parameter: expression) The lambda function returns the value of the expression by default. You can also assign it to a variable. A lambda function can accept any parameter, including optional arguments, but only one expression.

Extended reading:

https://www.zhihu.com/question/20125256

5.python How do I implement a singleton mode?

A: The singleton mode is a common software design pattern. In its core structure, it contains only a special class called a singleton class. The singleton mode can ensure that a class in the system has only one single case and that the single case is easy to access, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system.

__new__ () is called before __init__ () to generate the instance object. Using this method and the characteristics of the tired properties can realize the design pattern of the singleton mode. Singleton mode refers to the creation of unique objects, and the singleton pattern design class can only be instantiated.

1. Using the __new__ method

Class Singleton (object):  def __new__ (CLS, *args, **kw):      If not hasattr (CLS, ' _instance '):          orig = Super ( Singleton, CLS)          cls._instance = orig.__new__ (CLS, *args, **kw)      return cls._instanceclass MyClass (Singleton):  A = 1

2. Shared Properties

Class Borg (object):  _state = {}  def __new__ (CLS, *args, **kw):      ob = Super (Borg, CLS). __new__ (CLS, *args, **kw )      ob.__dict__ = cls._state      return obclass MyClass2 (Borg):  a = 1

3. Adorner version

Def Singleton (CLS, *args, **kw):  instances = {}  def getinstance ():      If CLS not in instances:          instances[ CLS] = CLS (*args, **kw)      return INSTANCES[CLS]  return getinstance@singletonclass MyClass: ...

4.import method

Class My_singleton (object):  def foo (self):      Passmy_singleton = My_singleton () # to Usefrom Mysingleton import My_ Singletonmy_singleton.foo ()

Extended reading:

17426543

6.python Introspection

A: Introspection is the object-oriented language written by the program at run time, can know the type of object, a simple sentence is the type of object can be obtained at runtime, such as type (), dir (), GetAttr (), hasattr (), Isinstance ().

A = [1,2,3]b = {' A ': 1, ' B ': 2, ' C ': 3}c = Trueprint type (a), type (b), type (c) # <type ' list ' > <type ' dict ' > <type ' BOOL ' >print isinstance (a,list)  # True

Extended reading:

https://kb.cnblogs.com/page/87128/

7. A talk about Python's decorator

A: The adorner is essentially a Python function that allows other functions to add extra functionality without any changes, and the return value of the adorner is also a function object. It is often used for scenes with demand for facets. For example: Insert log, performance test, transaction processing, caching, permission validation, etc. With adorners, we can pull out a lot of similar code that is unrelated to function function to reuse.

Extended read: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014318435599930270c0381a3b44db991cd6d858064ac0000

8. What is duck type?

A: 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 apply to duck types, 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 SWI M ... ') 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 ...

Extended reading:

40270009

[email protected] and @staticmethod

A: The function that corresponds to the @classmethod modifier does not need to be instantiated, does not require the self parameter, the first parameter needs to be a CLS parameter that represents its class, the CLS parameter can be used to invoke the class's properties, the class's methods, instantiate the object, and so on. @staticmethod a static method that returns a function that does not force a parameter to be passed, declares a static method as follows:

Class C (object):

@staticmethod

Def f (arg1, arg2,...):

...

The above example declares a static method F, the class can call the method c.f () without instantiation, or it can invoke C (). f () after instantiation.

Extended reading:

https://zhuanlan.zhihu.com/p/28010894

10. Talk about the meta-class in Python

A: In general, we define classes in code, creating instances with defined classes. Instead of using the meta-class, the steps are the same, define the meta-class, create the class with the meta-class, and then create the instance using the created class. The primary purpose of the meta-class is to automatically change the class when the class is created.

Extended reading:

66972933

    • Source: Datacastle Data Castle

    • Https://mp.weixin.qq.com/s/6LAlubLiTe-vxcoatQSEnQ

Python Interview Guide (hi-talk)

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.