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

How to use Python to write decorator

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

Share

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

This article mainly explains "how to use Python to write decorator", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to use Python to write decorator" bar!

Write the corresponding function according to the requirements of the topic.

Requirement: write a function and pass in a list of several integers, in which an element appears more than 50%, and returns this element.

Def more_than_half (items):

Temp, times = None, 0

For item in items:

If times = = 0:

Temp = item

Times + = 1

Else:

If item = = temp:

Times + = 1

Else:

Times-= 1

Return temp

Comments: the questions on LeetCode, which appeared in the Python interview, take advantage of the fact that the number of elements is more than 50%. If there are the same elements as temp, the count value will be increased by 1, and if there are different elements from temp, the count value will be reduced by 1. If the count value is 0, the previous element has no effect on the final result. Write down the current element with temp and set the count value to 1. Eventually, the element with more than 50% occurrences must be assigned to the variable temp.

Write the corresponding function according to the requirements of the topic.

Requirement: write a function that passes in a list (the elements in the list may also be a list) and returns the maximum nesting depth of the list. For example, the nesting depth of the list [1,2,3] is 1, and the nesting depth of the list [[1], [2, [3] is 3.

Def list_depth (items):

If isinstance (items, list):

Max_depth = 1

For item in items:

Max_depth = max (list_depth (item) + 1, max_depth)

Return max_depth

Return 0

Comments: when you see a topic, it should be natural to check every element in the list recursively.

Write the corresponding decorator according to the requirements of the topic.

Requirement: there is a function to obtain data through the network (an exception may occur due to network reasons). Write a decorator so that this function can retry a specified number of times when a specified exception occurs, and delay for a random period of time before each retry, and the maximum delay time can be controlled by parameters.

Method 1:

From functools import wraps

From random import random

From time import sleepdef retry (*, retry_times=3, max_wait_secs=5, errors= (Exception,)):

Def decorate (func):

@ wraps (func)

Def wrapper (* args, * * kwargs):

For _ in range (retry_times):

Try:

Return func (* args, * * kwargs)

Except errors:

Sleep (random () * max_wait_secs)

Return None

Return wrapper

Return decorate

Method 2:

From functools import wraps

From random import random

From time import sleepclass Retry (object):

Def _ _ init__ (self, *, retry_times=3, max_wait_secs=5, errors= (Exception,)):

Self.retry_times = retry_times

Self.max_wait_secs = max_wait_secs

Self.errors = errors

Def _ _ call__ (self, func):

@ wraps (func)

Def wrapper (* args, * * kwargs):

For _ in range (self.retry_times):

Try:

Return func (* args, * * kwargs)

Except self.errors:

Sleep (random () * self.max_wait_secs)

Return None

Return wrapper

Comments: we have emphasized more than once that the decorator is almost a must-ask for a Python interview. This topic is a little more complicated than the previous one. It requires a parameterized decorator.

Write a function to reverse the string and write as many methods as you can.

Comments: the title of Bad Street is basically the topic of giving people a head.

Method 1: reverse slice

Def reverse_string (content):

Return content [::-1]

Method 2: reverse splicing

Def reverse_string (content):

Return'. Join (reversed (content))

Method 3: call recursively

Def reverse_string (content):

If len (content) 1:

Yield idx + 1000 Thank you for your reading, the above is the content of "how to use Python to write decorator". After the study of this article, I believe you have a deeper understanding of how to use Python to write decorator, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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