In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the suggestions to improve the Python program?" in the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1: introduction
Suggestion 1. Understand the concept of Pythonic-see "Zen of Python" in Python for details
Recommendation 2. Write Pythonic code
(1) avoid irregular code, such as using only case-sensitive variables, using confusing variable names, being afraid of long variable names, and so on. Sometimes long variable names make the code more readable.
(2) in-depth study of Python-related knowledge, such as language features, library features, such as the evolution of Python. Learn more about one or two Pythonic code bases recognized in the industry, such as Flask, etc.
Tip 3: understand the differences between Python and C, such as indentation and {}, single quotation marks, double quotes, ternary operators? , Switch-Case statements, etc.
Recommendation 4: add comments to your code as appropriate
Recommendation 5: it is more reasonable to add empty exercise code layout appropriately.
Recommendation 6: four principles for writing functions
(1) the function design should be as short as possible, and the nesting level should not be too deep.
(2) function declaration should be reasonable, simple and easy to use.
(3) downward compatibility should be considered in the design of function parameters.
(4) A function does only one thing to ensure the consistency of function granularity as far as possible.
Recommendation 7: centralize constants in one file and use all uppercase letters for constant names as much as possible
2: programming idioms
Recommendation 8: use assert statements to find problems, but be aware that assertions assert can affect efficiency
Recommendation 9: temporary variables are not recommended for data exchange values, but directly a, b = b, a
Recommendation 10: make full use of the characteristics of lazy computing (Lazy evaluation) to avoid unnecessary calculations
Recommendation 11: understand the shortcomings of enumerated alternative implementations (enumeration features have been added to the latest version of Python)
Recommendation 12: type is not recommended for type checking because sometimes type results are not necessarily reliable. If there is a need, it is recommended to use the isinstance function instead of
Recommendation 13: try to convert the variable to a floating-point type before dividing (don't think about it later on Python3)
Recommendation 14: beware of security vulnerabilities in the eval () function, which is somewhat similar to SQL injection
Recommendation 15: use enumerate () to get both the index and the value of the sequence iteration
Recommendation 16: distinguish between the applicable scenarios of = = and is, especially when comparing immutable type variables such as strings (see comments for details)
Recommendation 17: try to use Unicode. Coding in Python2 is a headache, but Python3 doesn't have to think too much about it.
Recommendation 18: build a reasonable package hierarchy to manage Module
3: basic usage
Recommendation 19: use from in moderation. Import statement to prevent pollution of namespaces
Recommendation 20: use absolute import to import modules first (relative import has been removed from Python3)
It is recommended that 21:i+=1 is not equal to + + I. In Python, the plus sign before + + I only indicates positive, not operation.
Recommendation 22: get used to using with to automatically close resources, especially when reading and writing files
Recommendation 23: use the else clause to simplify the loop (exception handling)
Recommendation 24: follow several basic principles of exception handling
(1) pay attention to the granularity of exceptions and write as little code as possible in try blocks
(2) be careful to use separate except statements, or except Exception statements, but locate specific exceptions
(3) pay attention to the order of exception capture and handle exceptions at the appropriate level.
(4) use more friendly exception information and abide by the specification of exception parameters.
Recommendation 25: avoid pitfalls that may occur in finally
Recommendation 26: have a deep understanding of None and correctly determine whether the object is empty. The following data in Python is judged to be empty:
Recommendation 27: the connection string should give priority to the join function rather than the + operation
Recommendation 28: try to use the .format function instead of% when formatting strings
Recommendation 29: distinguish between mutable and immutable objects, especially as function arguments
Recommendation 30: [], {} and (): consistent container initialization form. Using list parsing can make the code clearer and more efficient
Recommendation 31: function passes parameters, neither values nor references, but objects or references to objects
Recommendation 32: beware of potential problems with default parameters, especially if the default parameter is a mutable object
Recommendation 33: use variable length parameters args and * kargs carefully in functions
(1) this kind of use is so flexible that the function signature is not clear enough and the readability is poor.
(2) if the definition of the function is simplified with variable length parameters because of too many parameters, the function can be reconstructed.
Recommendation 34: learn more about the difference between str () and repr ()
(1) the goal between the two is different: str is mainly customer-oriented, its purpose is readability, and the return form is in the form of a string with high user-friendliness and readability, while repr is for Python interpreters or Python developers, and its purpose is accuracy, and its return value represents the internal definition of the Python interpreter.
(2) enter variables directly into the interpreter and call the repr function by default, while print (var) calls the str function by default
(3) the return value of the repr function can generally use the eval function to restore the object.
(4) the two call the object's built-in functions str__ () and _ _ repr (), respectively.
Recommendation 35: distinguish between static method staticmethod and class method classmethod usage scenarios
4: library
Suggestion 36: master the basic use of strings
Recommendation 37: select the sort () and sorted () functions as needed
"sort () sorts the list in place, so you cannot sort immutable types such as tuples.
"sorted () can sort any iterable type without changing the original variable itself.
Recommendation 38: use copy module deep copy objects to distinguish between shallow copy (shallow copy) and deep copy (deep copy)
Recommendation 39: use Counter for counting, Counter is a subclass of the dictionary class, in the collections module
Recommendation 40: learn more about ConfigParser
Recommendation 41: use the argparse module to handle command line arguments
Recommendation 42: use pandas to deal with large CSV files
Python itself provides a CSV file processing module and provides functions such as reader, writer, and so on.
"Pandas can provide blocking, merging, etc., which is suitable for the case of large amount of data, and is more convenient for two-dimensional data operation.
Recommendation 43: use ElementTree to parse XML
Recommendation 44: understand the pros and cons of the module pickle
"advantages: simple interface, common platforms, wide range of data types and strong expansibility
"disadvantages: no guarantee of atomicity of data manipulation, security problems, incompatibility between different languages
Recommendation 45: another choice for serialization: JSON modules: load and dump operations
Recommendation 46: use traceback to get stack information
Recommendation 47: use logging to log information
Recommendation 48: write multithreaded programs using threading modules
Recommendation 49: use the Queue module to make multithreaded programming safer
5: design pattern
Recommendation 50: use modules to implement singleton mode
Recommendation 51: use mixin mode to make programs more flexible
Recommendation 52: loose coupling with publish-subscribe pattern
Recommendation 53: beautify the code with state mode
6: internal mechanism
Recommendation 54: understand build-in objects
Suggestion 55 _ new _ () is not a construction method, understand the difference between _
Recommendation 56: understand the variable lookup mechanism, that is, scope
"Local scope
"Global scope
"nested scope
"built-in scope
Recommendation 57: why the self parameter is required
Recommendation 58: understand MRO (method parsing order) and multiple inheritance
Recommendation 59: understand the descriptor mechanism
Recommendation 60: distinguish the difference between the getattr__ () and _ _ getattribute () methods
Recommendation 61: use a more secure property
Recommendation 62: master metaclass metaclass
Recommendation 63: be familiar with Python object protocol
Recommendation 64: implement infix syntax using operator overloading
Recommendation 65: be familiar with Python's iterator protocol
Recommendation 66: be familiar with Python generators
Recommendation 67: understand the differences between collaborators, multithreading, and multiprocesses based on the generator's co-programs and greenlet
Recommendation 68: understand the limitations of GIL
Recommendation 69: object management and garbage collection
7: use tools to assist project development
Recommendation 70: install third-party packages from PyPI
Recommendation 71: install and manage packages using pip and yolk
Suggestion 72: do paster to create a package
Recommendation 73: understand the concept of unit testing
Recommendation 74: write unit tests for packages
Recommendation 75: use test-driven development (TDD) to improve the testability of code
Recommendation 76: check the code style using Pylint
"Code style review
"Code error checking
"find repetitive and unreasonable code to facilitate refactoring
"highly configurable and customizable
"support the integration of various IDE and editors
"ability to generate UML diagrams based on Python code
"can be combined with continuous integration tools such as Jenkins to support automatic code review
Recommendation 77: conduct efficient code review
Recommendation 78: publish the package to PyPI
8: performance analysis and optimization
Recommendation 79: understand the basic principles of code optimization
Recommendation 80: with performance optimization tools
Recommendation 81: use cProfile to locate performance bottlenecks
Recommendation 82: use memory_profiler and objgraph to profile memory usage
Recommendation 83: strive to reduce the complexity of the algorithm
Suggestion 84: master the basic skills of cycle optimization
"reduce the calculation inside the loop
"change an explicit loop to an implicit loop, which of course sacrifices the readability of the code
"try to reference local variables in the loop
"focus on inner nested loops
Recommendation 85: use generators to improve efficiency
Recommendation 86: optimize performance with different data structures
Recommendation 87: take full advantage of set
Recommendation 88: use the multiprocessing module to overcome GIL defects
Recommendation 89: use thread pools to improve efficiency
Recommendation 90: improve performance with the extension of the CumberCandle + module
Recommendation 91: write extension modules in Cythonb
This is the end of the content of "what are the suggestions for improving the Python program"? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.