SoFunction
Updated on 2024-11-17

Python Decorator Usage and Knowledge Summary

This article is an example of Python decorator usage and knowledge. Shared for your reference, as follows:

(1) Decorator with parameters, decorated function without (with) parameters

The example code is as follows:

import time
# Decorator functions
def wrapper(func):
  def done(*args,**kwargs):
    start_time = ()
    func(*args,**kwargs)
    stop_time = ()
    print('the func run time is %s' % (stop_time - start_time))
  return done
# Decorated function 1
@wrapper
def test1():
  (1)
  print("in the test1")
# Decorated function 2
@wrapper
def test2(name):  #1.test2===>wrapper(test2)  2.test2(name)==dome(name)
  (2)
  print("in the test2,the arg is %s"%name)
# Call
test1()
test2("Hello World")

(2) Decorator with parameters, decorated function with (without) parameters

import time
user,passwd = 'admin','admin'
def auth(auth_type):
  print("auth func:",auth_type)
  def outer_wrapper(func):
    def wrapper(*args, **kwargs):
      print("wrapper func args:", *args, **kwargs)
      if auth_type == "local":
        username = input("Username:").strip()
        password = input("Password:").strip()
        if user == username and passwd == password:
          print("\033[32;1mUser has passed authentication\033[0m")
          res = func(*args, **kwargs) # from home
          print("---after authenticaion ")
          return res
        else:
          exit("\033[31;1mInvalid username or password\033[0m")
      elif auth_type == "ldap":
        print("ldap link")
    return wrapper
  return outer_wrapper
@auth(auth_type="local") # home = wrapper()
def home():
  print("welcome to home page")
  return "from home"
@auth(auth_type="ldap")
def bbs():
  print("welcome to bbs page"
print(home()) #wrapper()
bbs()

Summary:

(1) The decorator is essentially a function inline that returns the address of the function.

(2) decorator with parameters and without parameters compared to the decorator with parameters with an additional layer of function definition used to receive the parameters passed in the decorator, the rest is basically the same.

(3) Validate the parameters in the decorator first, and then validate the parameters in the normal function

Trivia:

List production style: [i for i in range(5)]---->[0,1,2,3,4,5]

Generators and Iterators:

The first way is generated by bracketing

Generator: ()---(i for i in range(5)) ==>generator

This mechanism of calculating while looping is called generator: generator.

The generator only generates the appropriate data when called and only records the current position.

There is only one __next__() method

The second way is generated via yield

Use yield in a function to turn a function into a generator.

Iterator:

The data type that acts directly on the for loop:

One class is collection data types, such as list, tuple, dict, set, str, and so on;

One class is generator, which includes generators and generator functions with yield.

Objects that act directly on the for loop are collectively called iterable objects: Iterable.

You can use isinstance() to determine whether an object is an Iterable object or not

from collections import Iterable
 isinstance([], Iterable)=========true

*An object that can be called by the next() function and keeps returning the next value is called an iterator: Iterator.

You can use isinstance() to determine whether an object is an Iterator object:

>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
======>True

The generators are all Iterator objects, but list, dict, and str are not Iterators even though they are Iterable.

To turn an Iterable such as list, dict, str, etc. into an Iterator you can use the iter() function:

Example: iter([])<==== iterator

Python's Iterator object represents a stream of data. The Iterator object can be called by the next() function and keeps returning the next data until it throws a StopIteration error when there is no data. The data stream can be viewed as an ordered sequence, but we can not know the length of the sequence in advance, only through the next () function to achieve on-demand calculation of the next data, so the calculation of the Iterator is inert, only in the need to return to the next data it will calculate.

Iterator can even represent an infinite stream of data, such as the whole natural numbers. You can never store the whole natural numbers using a list.

Summary:

Any object that can act on a for loop is of type Iterable;

Any object that can act on the next() function is of type Iterator, and they represent a sequence of inert computations;

Collection datatypes such as list, dict, str, etc. are Iterable but not Iterator, although you can get an Iterator object through the iter() function.

Readers interested in more Python related content can check out this site's topic: thePython Object-Oriented Programming Introductory and Advanced Tutorials》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Summary of Python coding manipulation techniquesand thePython introductory and advanced classic tutorials

I hope that what I have said in this article will help you in Python programming.