Write efficient and elegant PYTHON code

Source: Internet
Author: User
Tags generator

1, List push to type:

For simple function methods, use a table deduction instead of the map and filter functions as much as possible, because there are often fewer functions.

For example

nums= [1, 2, 3]

Squares = map (lambda x:x**2, nums) #使用map

Squares = [x**2 for x in Test_num] #使用列表推导式

Moreover, many judgments can be added to the list derivation.

    Squares = [x**2 for x in test_num if x = = 2] #使用列表推导式, equivalent to using filter

However, if the method is too complex, it is recommended that you use the map function

If you have too much data, you can use a generator expression instead of a list deduction to save a lot of memory

    Squares = (x**2 for x in test_num if x = = 2) #使用生成器表达式来代替列表式, which consumes memory when used

2, use the ZIP function to iterate over two lists of different lengths at a time

 The main function of the ZIP function is to package the contents of one or more iterators to generate an L-tuple, and to pass in multiple iterators at the same time. If the number of elements in each iterator is inconsistent, the returned list is the same length as the shortest object.

Test_num = [1, 2, 3]

test_num2 = [' A ', ' B ', ' C ', ' d ']

For I in Zip (Test_num, test_num2):

Print I


3, using adorners:
Adorners are used to modify existing functions without changing the original function code. A common scenario is to add a debug or add log monitoring to an existing function, depending on my previous blog

4, using a build instead of a return list
A function with yield is the ability to push the value of a value into a build, which is evaluated when the build is actually called. The yield field must be used in the function, and then the return value of the call to the function will be a build, only when called
To calculate the series, which greatly reduces the memory
But! The generator can only be iterated once, and once the loop is over, the iterator is invalidated and can only be reused for later use
If you do not want to cause the results above, you can pass the result of the generator into a class of repeatable iterations: for example:
  
classLoopiter(object):  def    __init__    (self, data): Self.data=data    # must yield results in __iter__    def    __iter__    (self):    for index,letter   in Enumerate (self.data):    if letter = =    ' a ':     yield index# record subscript  

5, this way you can record several unused built-in parameters:
__slots__
  This built-in parameter records all parameters used in this class, and the parameters of the class can be dynamically added by default, but if the parameter is fixed as a list, you cannot dynamically increment the parameter

__call __
This built-in method allows an instance object to invoke the method of the instance as called by the method
Python's   __call__   method allows an instance of a class to behave like a function. Typically used to define and initialize some function with context
  class A (object):  
def __call__ (self, *args, **kwargs):
print args
a = A ()
A ("123")
temporarily does not understand the benefits of doing so, which in effect blurs the relationship between the function and the instance object. The use scenario that can be used for reference on the network is that a class can be written as an adorner for invocation.
  class  Pipedef __init__ (self, fn): Self.fn = fn def __ror__ (self, other): return Self.fn (Other) def __call__ (self, *args, **kwargs): op = Pipe (return op      
   @Pipe  def sort (data, Cmp=none, Key=none, reverse=false): return sorted (data, cmp=cmp, Key=none, Reverse=reverse) [{ ' score ': 1}, { ' score ': 3}, { ' score ': 2}] | sort (key=lambda x:x[ ' score '])                  

__init__ functions and __NEW__ functions The

__init__ function is the first function to execute when a class is loaded, and is typically used to initialize the class
The __new__ function is the function used to create an instance, often, You can use this function to implement a singleton pattern:
Class Singleton (object):
_instance = None
Def __new__ (CLS, *args, **kw):
If not cls._instance:
Cls._instance = Super (Singleton, CLS). __new__ (CLS, *args, **KW)
Return cls._instance
Class MyClass (Singleton):
A = 1

@classmethod and @staticmethod
@staticmethod similar to defining a static method, this method does not pass in the relevant data of this class as a parameter
and the @classmethod annotation method, will pass the class itself as a parameter, the advantage is that I can not invade the original code for function operation

The context management function, __enter__ and __exit__ functions, can be used to define the methods that are executed when using the method that executes when entering the function and the Exit function, where the WITH keyword is used to invoke the function.
The classic scenario is to make the file read, using the WITH function to ensure that the file is opened and closed correctly

Reference Links:
Https://gnu4cn.gitbooks.io/python-advance-coding/content/01-effective-and-fine-python-code.html



 




  
  

Write efficient and elegant PYTHON code

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.