Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the functions of Python3

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the functions of Python3". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the functions of Python3"?

1. Enumerate

Python 3 allows you to write enumerations in the Enum class in a simple way. Enumerations consist of class syntax that simplifies the process of reading and writing, but without any structure-the code is not easy to generate.

From enum import Enum, auto class Fruit (Enum): APPLE = auto () ORANGE = auto () GUAVA = auto () print (Fruit.APPLE) # Fruit.APPLE

When the exact value is trivial, you can use an automatic value instead.

An enumeration is a collection of symbolic items (members) associated with a specific fixed value. In enumerations, symbol names can be distinguished by naming and individually iterating enumerations.

For fruit in Fruit: print (fruit)-> Fruit.APPLE-> Fruit.ORANGE-> Fruit.GUAVA

Minimum Python version: 3.4

two。 Type hint

Compared with dynamic, static typing is a hot topic in computer language, and everyone has his own opinion on it. I will allow the viewer to consider when to write the type. However, I think you must understand the Python 3 support type hint.

Def fruits_word (line: str)-> bool: return "fruit" in line test = fruits_word ("I love to eat fresh fruits") print (test) # True

Minimum Python version: 3.5

3. Pathlib

F strings are incredible, but strings such as file paths have their own libraries that make it easier to manipulate them. The Pathlib module simplifies complex situations and optimizes some simple ones. As a convenient abstraction for working with file paths, Python 3 provides pathlib.

From pathlib import Path root = Path ('blog_new_folder') print (root) # blog_new_folder path = root /' new_program' print (path.resolve ()) # / home/vivekcoder/Workspace/My_Programming/Medium-Articles/python3_uncommon_features/blog_new_folder/new_program

I think this article will inspire you to use the Python Pathlib module when you need to work with Python files.

Minimum Python version: 3.4

4. F-Strings

In the absence of strings, it is difficult for any programming language to do anything, and you want to use strings in a structured way to stay efficient. Most people who use Python prefer the format method.

Import datetime name = "Leijie" activity = "writing Toutiao article" time = datetime.date (2020, 8,15) message ='My name is {}, I completed an activity {} on {}. '.format (name, activity, time) print (message) # My name is Leijie, I completed an activity writing Toutiao article on 2020-08-15.

In addition to the format, Python 3 provides a general way to interpolate strings through f strings. The above code with the f string is as follows:

Import datetime name = "Leijie" activity = "writing Toutiao article" time = datetime.date (2020, 8,15) message = f'My name is {name}, I completed an activity {activity} on {time:%A,% B% d,% Y}. Print (message) # My name is Leijie, I completed an activity writing Toutiao article on Saturday, August 15, 2020.

Code created by F-Strings is even easier to understand and use than using string concatenation or formatting strings.

The F string allows you to integrate expressions into string literals with minimal syntax. It should be noted that f-Strings is actually a run-time expression, not a fixed value.

Minimum Python version: 3.6

5. Built-in LRU cache

If the latest call is the best predictor for incoming calls, LRU (least recently used) will have good caching performance. (for example, the most common news server posts change every day.) The size limit of the cache means that if there are no long-running loops like the Web server, the cache will not expand.

When defining a user function, it must be callable. This makes it possible to apply the lru_cache decorator directly to user functions in Python 3.

Here is an example of a Fibonacci function that we know will benefit from caching because it can do the same thing multiple times through recursion.

Import time def fibon (number: int)-> int: if number = = 0: return 0 if number = = 1: return 1 return fibon (number-1) + fibon (number-2) start = time.time () fibon (20) print (f'Duration: {time.time ()-start} s')-> Duration: 0.007005214691162109s

Here, we can configure it using lru-cache. This optimization method is called a memo. The decorator includes a callable function with a memo that stores the maximum size of the most recently called.

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 (20) print (f'Duration: {time.time ()-start} s')-> Duration: 4.341516078231e-09s

Minimum Python version: 3.2

6. Extended repeatable unpacking

I will allow the code to respond below. An example describes the feature, which is better than 1000 words:

X, * y, z = range (4) print (x, y, z) # 0 [1,2] 3 python_version, file_name, topic, * output = "python3.0 hello.py betterprogramming 1 2 3 4" .split () print (python_version) print (file_name) print (topic) print (output) # python3.0 # hello.py# betterprogramming# ['1,'2,'3,'4] a, b, c, * d = range (7) print (b D) # 1 [3,4,5,6]

Minimum Python version: 3.0

For more information about the iterative decompression of extensions, see the official Python 3 documentation here.

7. Underlining in numeric text

Python 3.6provides an exciting way to help read numeric text by emphasizing numbers. It can be used to describe, for example, thousands, hexadecimal and binary numbers.

Price = 50,000 print (f'Price: {price}') # Price: 50000 hexa_val = 0xABCD_EFD9 print (f'Decimal equivalent: {hexa_val}') # Decimal equivalent: 2882400217 bin_ary = 0b_0010_0110 print (f'Decimal: {bin_ary}') # Decimal: 38

Minimum Python version: 3.6

8. Assignment expression-Walrus operator

In the latest version of Python, the walrus operator is introduced, which assigns variables to expressions. If you plan to reference skins later in your code, it may be helpful and save one or two lines of code.

Birds = ['owl',' hen', 'duck',' parrot'] for bird in birds: if (len_bird: = len (bird)) > 4: print (Faira bird "{bird}" consists of "{len_bird}", letters') # A bird "parrot" consists of "6", letters

Minimum Python version: 3.8

9. Data class

The data classes provided by Python 3 have few restrictions and can be used to reduce boilerplate code because the decorator automatically generates unique methods such as _ _ init _ () and _ _ repr _ (). The official proposal lists it as a "variable named tuple with default values".

Class Item_list: def _ init__ (self, name: str, perunit_cost: float, quantity_available: int = 0): self.name = name self.perunit_cost = perunit_cost self.quantity_available = quantity_available def total_cost (self)-> float: return self.perunit_cost * self.quantity_available book = Item_list ("better programming." 50 2) x = book.total_cost () print (x) # 100 print (book) #

Using the @ dataclass decorator, you can write the same implementation:

From dataclasses import dataclass @ dataclassclass Item_list: name: str perunit_cost: float quantity_available: int = 0 def total_cost (self)-> float: return self.perunit_cost * self.quantity_available book = Item_list ("better programming.", 50,2) x = book.total_cost () print (x) # 100 print (book) # Item_list (name='better programming.', perunit_cost=50, quantity_available=2)

Minimum Python version: 3.7

At this point, I believe you have a deeper understanding of "what are the functions of Python3?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report