In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Python3 what are the hidden skills you haven't get yet? for this question, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.
Python3, hidden skills that you haven't get yet.
After the introduction of Python 3, people began to gradually migrate Python 2-based code to Python 3. However, during the migration process, many of the code failed to use the new features provided by Python 3. Here is an introduction to related features, including string formatting, file path handling, type hints, built-in LRU caching, etc., to help you better use Python 3 to write code.
As Python 2 is about to retire from history, many people have begun to convert the code of Python 2 to Python 3, but in the process of this change, people seem to have just added a few more parentheses, and most people have not noticed the exciting new features in Python 3. Here are some interesting features in Python 3, which I hope will help you solve some problems more easily.
[note]: the code examples in this article are based on Python 3.7. for ease of use, the minimum Python version required for this feature is listed at the end of each feature.
F-strings (3.6 +)
String processing is a very important content for any programming language, and string processing is often the basic part of many programs. Because manual processing of strings is very tedious, we prefer to deal with them in a structured way. In Python, we generally use format for structured string processing, as shown below:
User = "Jane Doe" action = "buy" log_message = 'User {} has logged in and did an action {}.' .format (user, action) print (log_message) # User Jane Doe has logged in and did an action bu
In addition to format, Python 3 provides a more flexible way to deal with strings, which is f-string. As shown below, we use f-string to implement the same function as the above code:
User = "Jane Doe" action = "buy" log_message = f'User {user} has logged in and did an action {action}. 'print (log_message) # User Jane Doe has logged in and did an action buy.
Pathlib (3.4 +)
If we need to deal with file paths, we can use the pathlib library in Python 3 to make it easier to manipulate file paths. If you have any doubts about pathlib, you can refer to this article. A code example is provided below:
From pathlib import Pathroot = Path ('post_sub_folder') print (root) # post_sub_folderpath = root /' happy_user'# Make the path absoluteprint (path.resolve ()) # / home/weenkus/Workspace/Projects/DataWhatNow-Codes/how_your_python3_should_look_like/post_sub_folder/happy_user
Type hint (3.5 +)
Static and dynamic typing is a hot topic in software engineering. Python 3 provides methods to support type hinting (type hints). Here is an example:
Def sentence_has_animal (sentence: str)-> bool: return "animal" in sentencesentence_has_animal ("Donald had a farm without animals") # True
Enumeration (3.4 +)
The Enum class in Python 3 supports enumeration, which makes our program more concise. Enum is a convenient way to package a list of variables, using this method can avoid multiple variables distributed throughout the code, making the code appear disorganized.
From enum import Enum, autoclass Monster (Enum): ZOMBIE = auto () WARRIOR = auto () BEAR = auto () print (Monster.ZOMBIE) # Monster.ZOMBIE
An enumeration is a collection of symbols, each corresponding to a unique variable. By using enumerations, we can compare members by symbolic identifiers, and we can iterate over the enumerations themselves.
Https://docs.python.org/3/library/enum.htmlfor monster in Monster: print (monster) # Monster.ZOMBIE# Monster.WARRIOR# Monster.BEAR
Built-in LRU cache (3.2 +)
Caching is ubiquitous in today's hardware and software. Python 3 uses LRU (Least Recently Used) caching through lru_cache.
The following code defines a Fibonacci function, and because the operation of this function requires multiple recursions, each recursion performs the same work, so using caching can speed up its calculation.
Import timedef fib (number: int)-> int: if number = = 0: return 0 if number = = 1: return 1 return fib (number-1) + fib (number-2) start = time.time () fib (40) print (f'Duration: {time.time ()-start} s') # Duration: 30.684099674224854s
We can use lru_cache to optimize this operation. This optimization pole technique, called memoization, reduces execution time from a few seconds to a few nanoseconds.
From functools import lru_cache@lru_cache (maxsize=512) def fib_memoization (number: int)-> int: if number = = 0: return 0 if number = = 1: return 1 return fib_memoization (number-1) + fib_memoization (number-2) start = time.time () fib_memoization (40) print (f'Duration: {time.time ()-start} s') # Duration: 6.866455078125e-05s
Extended iterative parsing function (3.0 +)
Do not make a detailed explanation here, directly post the sample code, the specific solution can refer to this document.
Head, * body, tail = range (5) print (head, body, tail) # 0 [1, 2, 3] 4py, filename, * cmds = "python3.7 script.py-n 5-1 15" .split () print (py) print (filename) print (cmds) # python3.7# script.py# ['- n, 5,'- lump,'15'] first, _, third, * _ = range (10) print (first, third) # 0
Data class (3.7 +)
Python 3 introduces data classes (data class). Its decorator automatically generates feature methods, such as _ _ init__ () and _ _ repr () _ _, which can help reduce the amount of sample code. In official documentation, they are called "variable named tuples with default values".
Class Armor: def _ init__ (self, armor: float, description: str, level: int = 1): self.armor = armor self.level = level self.description = description def power (self)-> float: return self.armor * self.levelarmor = Armor (5.2, "Common armor.", 2) armor.power () # 10.4print (armor)
Next let's use the data class to implement the above code:
From dataclasses import dataclass@dataclassclass Armor: armor: float description: str level: int = 1 def power (self)-> float: return self.armor * self.level armor= Armor (5.2, "Common armor.", 2) armor.power () # 10.4print (armor) # Armor (armor=5.2, description='Common armor.', level=2
Implicit Namespace package (3.3 +)
There are many ways to build Python code, one of which is to build it in a packages (that is, a folder containing an init.py file). The following example is provided by the official documentation of Python:
Sound/ Top-level package _ _ init__.py Initialize the sound package formats/ Subpackage for file format conversions _ _ init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py... Effects/ Subpackage for sound effects _ _ init__.py echo.py surround.py reverse.py... Filters/ Subpackage for filters _ _ init__.py equalizer.py vocoder.py karaoke.py...
In Python 2, each of the above folders must have an init.py file, which is used to convert its folder into a Python package. In Python 3, however, by using the implicit Implicit Namespace Package: https://www.python.org/dev/peps/pep-0420/, these files are no longer needed.
Sound/ Top-level package _ _ init__.py Initialize the sound package formats/ Subpackage for file format conversions wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py... Effects/ Subpackage for sound effects echo.py surround.py reverse.py... Filters/ Subpackage for filters equalizer.py vocoder.py karaoke.py...
Note: the official document PEP 420 Specification points out that init.py is still required for some regular packages, and if the file is deleted, the Python package will be changed into a local namespace package, which will create some additional restrictions, as detailed in this document.
Summary
This is the answer to the question about what hidden skills you have not yet get about Python3. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
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.