程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python tips (3)

編輯:Python

19. Don't split multiple values returned by a function into more than three variables

Unpacking mechanism allows Python Function returns more than one value :

def get_stats(numbers): minimum = min(numbers) maximum = max(numbers) return minimum, maximumlengths = [63, 73, 72, 60, 67, 66, 71, 61, 72, 70]minimum, maximum = get_stats(lengths)print(f'Min: {minimum}, Max: {maximum}')>>>Min: 60, Max: 73

When returning multiple values , You can use an asterisk expression to receive values that are not captured by ordinary variables .

def get_avg_ratio(numbers): average = sum(numbers) / len(numbers) scaled = [x / average for x in numbers] scaled.sort(reverse=True) return scaledlongest, *middle, shortest = get_avg_ratio(lengths)print(f'Longest: {longest:>4.0%}')print(f'Shortest: {shortest:>4.0%}')>>>Longest: 108%Shortest: 89%

20. You should throw an exception when encountering an unexpected situation , Don't go back None

def careful_devide(a, b): try: return a / b except ZeroDivisionError: raise ValueError('Invalid inputs')x, y = 5, 2try: result = careful_devide(x, y)except ValueError: print('Invalid inputs')else: print('Result is %.1f' % result)>>>Result is 2.5

21. Learn how to use variables in peripheral scopes in closures

Python Support closure , This allows small functions defined in large functions to apply variables of large functions . Function in Python Medium time first-class objects , So you can refer to them directly as you operate on other objects 、 Assign them to variables 、 Pass them as parameters to other functions .Python In judging two sequences ( Include tuples ) The size of , Compare first 0 Two elements in position No , If equal , On the comparison 1 Two elements in position No , If it's still equal , On the comparison 2 Two elements in position No , And so on , Until we come to a conclusion .
Python There is a special way of writing , You can assign the data in the closure to variables outside the closure .

def sort_priority(numbers, group): found = False def helper(x): nonlocal found if x in group: found = True return (0, x) return (1, x) numbers.sort(key=helper) return found

22. Use a variable number of position parameters to design a clear parameter list for the function

def log(message, *values): if not values: print(message) else: values_str = ', '.join(str(x) for x in values) print(f'{message}: {values_str}')log('My numbers are', 1, 2)log('Hi there')>>>My numbers are: 1, 2Hi therefavorites = [7, 33, 99]log('Favorite colors', *favorites)>>>Favorite colors: 7, 33, 99

23. Use keyword parameters to represent optional behavior

def remainder(number, divisor): return number % divisor# The following four effects are the same remainder(20, 7)remainder(20, divisor=7)remainder(number=20, divisor=7)remainder(divisor=7, number=20)

If positional parameters and keyword parameters are mixed , Positional parameters must appear before keyword parameters .
If there is a dictionary , And remainder Function can call this dictionary , So you can take ** Add in front of the dictionary , It will make Python Pass the key value pairs in the dictionary to the function in the form of keyword parameters .

my_kwargs = { 'number': 20, 'divisor': 7,}remainder(**my_kwargs)my_kwargs = { 'divisor': 7,}remainder(number=20, **my_kwargs)my_kwargs = { 'number': 20,}other_kwargs = { 'divisor': 7,}remainder(**my_kwargs, **other_kwargs)

Calling functions with keyword parameters can make it easier for first-time readers to understand . Can have default values , This value is specified when defining the function . It can flexibly expand the parameters of the function .

24. use None and docstring To describe the parameters whose default values will change

def log(message, when=None): if when is None: when = datatime.now() print(f'{when}: {message}')
def decode(data, default=None): try: return json.loads(data) except ValueError: if default is None: default = {} return default

25. Design a clear parameter list with parameters that can only be specified by keywords and can only be passed in by location

def safe_division_e(numerator, denominator, /, ndigits=10, *, ignore_overflow=False, ignore_zero_division=False): try: fraction = numerator / denominator return round(fraction, ndigits) except OverflowError: if ignore_overflow: return 0 else: raise except ZeroDivisionError: if ignore_zero_division: return float('inf') else: raise

In the parameter list of the function ,/ The parameters on the left side of the symbol are parameters that can only be specified by position ,* The parameters on the right side of the symbol are parameters that can only be specified in the form of keywords . The parameters between these two symbols can be provided by position , You can also specify... In the form of keywords .

26. use functools.wraps Define a function modifier

This is a very useful mechanism , It ensures that users use functions in the right way , It can also be used to debug programs or register functions , In addition, there are many uses .

from functools import wrapsdef trace(func): @wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) print(f'{func.__name__}({args!r}, {kwargs!r}) ' f'-> {result!r}') return result return [email protected] fibonacci(n): """Return the n-th Fibonacci number""" if n in (0, 1): return n return (fibonacci(n - 2) + fibonacci(n - 1))help(fibonacci)>>>Help on function fibonacci in module __main__:fibonacci(n) Return the n-th Fibonacci number

author :yspg_217

Game programming , A game development favorite ~

If the picture is not displayed for a long time , Please use Chrome Kernel browser .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved