python测试开发面试常考题:装饰器

这篇具有很好参考价值的文章主要介绍了python测试开发面试常考题:装饰器。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

简介

Python 装饰器是一个可调用的(函数、方法或类),它获得一个函数对象 func_in 作为输入,并返回另一函数对象 func_out。它用于扩展函数、方法或类的行为。

装饰器模式通常用于扩展对象的功能。在日常生活中,这种扩展的例子有:在枪上加一个消音器,使用不同的相机镜头等等。

Django框架中有大量装饰器

  • 限制某些HTTP请求对视图的访问
  • 控制
  • 按单个视图控制压缩
  • 基于特定HTTP请求头控制缓存

Pyramid框架和Zope应用服务器也使用装饰器来实现各种目标。

  • 将函数注册为事件订阅者
  • 以特定权限保护一个方法
  • 实现适配器模式

应用

装饰器模式在跨领域方面大放异彩:

  • 数据验证
  • 缓存
  • 日志
  • 监控
  • 调试
  • 业务规则
  • 加密

使用修饰器模式的另一个常见例子是(Graphical User Interface,GUI)工具集。在GUI工具集中,我们希望能够将一些特性,比如边框、阴影、颜色以及滚屏,添加到组件/控件。

第一类对象

装饰器是Python中非常强大和有用的工具,它允许程序员修改函数或类的行为。装饰器允许我们封装另一个函数,以扩展被封装函数的行为,而不需要修改它。但在深入研究装饰器之前,让我们先了解一些概念,这些概念在学习装饰器时将会很有用。

在Python中,函数是第一类对象,这意味着 Python 中的函数可以作为参数使用或传递。

第一类函数的属性:

  • 函数是对象类型的实例
  • 可以将函数存储在变量
  • 可以将函数作为参数传递给其他函数
  • 可以从函数中返回函数。
  • 可以将它们存储在数据结构中,如哈希表、列表、...

例1:将函数视为对象。

def shout(text):
    return text.upper()
 
print(shout('Hello'))
 
yell = shout
 
print(yell('Hello'))

输出:

HELLO
HELLO

例2:将函数作为参数传递

def shout(text):
    return text.upper()
 
def whisper(text):
    return text.lower()
 
def greet(func):
    # storing the function in a variable
    greeting = func("""Hi, I am created by a function passed as an argument.""")
    print (greeting)
 
greet(shout)
greet(whisper)

输出:

HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.

例3: 从函数中返回函数。

def shout(text):
    return text.upper()
 
def whisper(text):
    return text.lower()
 
def greet(func):
    # storing the function in a variable
    greeting = func("""Hi, I am created by a function passed as an argument.""")
    print (greeting)
 
greet(shout)
greet(whisper)

输出:

25

参考资料

  • 本文涉及的python中文资源 请在github上点赞,谢谢!

  • 本文相关书籍下载

  • https://www.geeksforgeeks.org/decorators-in-python/

  • https://realpython.com/primer-on-python-decorators/

装饰器

如上所述,装饰器是用来修改函数或类的行为的。在装饰器中,函数被当作函数的参数,然后在封装函数中调用。

  • 装饰器的语法:
@gfg_decorator
def hello_decorator():
    print("Gfg")

'''Above code is equivalent to -

def hello_decorator():
    print("Gfg")
    
hello_decorator = gfg_decorator(hello_decorator)'''

gfg_decorator 是一个可调用的函数,它将在另一个可调用的函数hello_decorator函数上面添加一些代码,并返回封装函数。

  • 装饰器可以修改行为:

# defining a decorator
def hello_decorator(func):
 
    # inner1 is a Wrapper function in
    # which the argument is called
     
    # inner function can access the outer local
    # functions like in this case "func"
    def inner1():
        print("Hello, this is before function execution")
 
        # calling the actual function now
        # inside the wrapper function.
        func()
 
        print("This is after function execution")
         
    return inner1
 
 
# defining a function, to be called inside wrapper
def function_to_be_used():
    print("This is inside the function !!")
 
 
# passing 'function_to_be_used' inside the
# decorator to control its behaviour
function_to_be_used = hello_decorator(function_to_be_used)
 
 
# calling the function
function_to_be_used()

输出:

Hello, this is before function execution
This is inside the function !!
This is after function execution

让我们跳到另一个例子,在这个例子中,我们可以用装饰器轻松地找出函数的执行时间。

import time
import math
import functools
 
# decorator to calculate duration
# taken by any function.
def calculate_time(func):
     
    # added arguments inside the inner1,
    # if function takes any arguments,
    # can be added like this.
    @functools.wraps(func) # 支持内省,一般可以不用,多用于文档
    def inner1(*args, **kwargs):
 
        # storing time before function execution
        begin = time.time()
         
        func(*args, **kwargs)
 
        # storing time after function execution
        end = time.time()
        print("Total time taken in : ", func.__name__, end - begin)
 
    return inner1
 
 
 
# this can be added to any function present,
# in this case to calculate a factorial
@calculate_time
def factorial(num):
 
    # sleep 2 seconds because it takes very less time
    # so that you can see the actual difference
    time.sleep(2)
    print(math.factorial(num))
 
# calling the function.
factorial(10)

@functools.wraps装饰器使用函数functools.update_wrapper()来更新特殊属性,如__name__和__doc__,这些属性在自省中使用。

输出:

3628800
Total time taken in :  factorial 2.0061802864074707
  • 如果函数有返回或有参数传递给函数,怎么办?

在上面所有的例子中,函数都没有返回任何东西,所以没有问题,但人们可能需要返回的值。

def hello_decorator(func):
    def inner1(*args, **kwargs):
         
        print("before Execution")
         
        # getting the returned value
        returned_value = func(*args, **kwargs)
        print("after Execution")
         
        # returning the value to the original frame
        return returned_value
         
    return inner1
 
 
# adding decorator to the function
@hello_decorator
def sum_two_numbers(a, b):
    print("Inside the function")
    return a + b
 
a, b = 1, 2
 
# getting the value through return of the function
print("Sum =", sum_two_numbers(a, b))

输出:

before Execution
Inside the function
after Execution
Sum = 3

内部函数接收的参数是*args和**kwargs,这意味着可以传递任何长度的位置参数的元组或关键字参数的字典。这使得它成为通用的装饰器,可以装饰具有任何数量参数的函数。

  • 链式装饰器

链式装饰器是指用多个装饰器来装饰函数。

# code for testing decorator chaining
def decor1(func):
    def inner():
        x = func()
        return x * x
    return inner
 
def decor(func):
    def inner():
        x = func()
        return 2 * x
    return inner
 
@decor1
@decor
def num():
    return 10
 
@decor
@decor1
def num2():
    return 10
   
print(num())
print(num2())

输出

400
200

上面的例子类似于调用函数---

decor1(decor(num))
decor(decor1(num2))

一些常用的装饰器在 Python 中甚至是内建的,它们是 @classmethod, @staticmethod, 和 @property。@classmethod 和 @staticmethod 装饰器用于定义类命名空间中的方法,这些方法与该类的特定实例没有关系。@property装饰器是用来定制类属性的getters和setters的。

  • 类装饰器

在 Python 3.7 中的新的 dataclasses 模块中完成:

from decorators import debug, do_twice

@debug
@do_twice
def greet(name):
    print(f"Hello {name}")

语法的含义与函数装饰器相似。你可以通过写PlayingCard = dataclass(PlayingCard)来进行装饰。

类装饰器的一个常见用途是作为元类的一些使用情况的更简单的替代。

编写一个类装饰器与编写一个函数装饰器非常相似。唯一的区别是,装饰器将接收类而不是函数作为参数。事实上,你在上面看到的所有装饰器都可以作为类装饰器工作。

  • 带参数与不带参数的装饰器
def repeat(_func=None, *, num_times=2):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            for _ in range(num_times):
                value = func(*args, **kwargs)
            return value
        return wrapper_repeat

    if _func is None:
        return decorator_repeat
    else:
        return decorator_repeat(_func)

使用functools.partial也可达到类似效果。

以下是slowdown的演进版本

import functools
import time

def slow_down(_func=None, *, rate=1):
    """Sleep given amount of seconds before calling the function"""
    def decorator_slow_down(func):
        @functools.wraps(func)
        def wrapper_slow_down(*args, **kwargs):
            time.sleep(rate)
            return func(*args, **kwargs)
        return wrapper_slow_down

    if _func is None:
        return decorator_slow_down
    else:
        return decorator_slow_down(_func)
  • 有状态的装饰器
import functools

def count_calls(func):
    @functools.wraps(func)
    def wrapper_count_calls(*args, **kwargs):
        wrapper_count_calls.num_calls += 1
        print(f"Call {wrapper_count_calls.num_calls} of {func.__name__!r}")
        return func(*args, **kwargs)
    wrapper_count_calls.num_calls = 0
    return wrapper_count_calls

@count_calls
def say_whee():
    print("Whee!")

对函数的调用次数--存储在包装函数的函数属性 .num_calls 中。下面是使用它的效果:

>>> say_whee()
Call 1 of 'say_whee'
Whee!

>>> say_whee()
Call 2 of 'say_whee'
Whee!

>>> say_whee.num_calls
2

维护状态的典型方法是使用类装饰器。

import functools

class CountCalls:
    def __init__(self, func):
        functools.update_wrapper(self, func)
        self.func = func
        self.num_calls = 0

    def __call__(self, *args, **kwargs):
        self.num_calls += 1
        print(f"Call {self.num_calls} of {self.func.__name__!r}")
        return self.func(*args, **kwargs)

@CountCalls
def say_whee():
    print("Whee!")
  • 单例模式

单例是只有一个实例的类。比如 None、True 和 False,可以使用 is 关键字来比较 None。

import functools

def singleton(cls):
    """Make a class a Singleton class (only one instance)"""
    @functools.wraps(cls)
    def wrapper_singleton(*args, **kwargs):
        if not wrapper_singleton.instance:
            wrapper_singleton.instance = cls(*args, **kwargs)
        return wrapper_singleton.instance
    wrapper_singleton.instance = None
    return wrapper_singleton

@singleton
class TheOne:
    pass

如你所见,这个类装饰器与我们的函数装饰器遵循相同的模板。唯一的区别是,我们使用 cls 而不是 func 作为参数名,以表明它是类装饰器。

让我们看看它是否有效:

>>> first_one = TheOne()
>>> another_one = TheOne()

>>> id(first_one)
140094218762280

>>> id(another_one)
140094218762280

>>> first_one is another_one
True

注意:在Python中,单例其实并不像其他语言那样经常使用,通常用全局变量来实现更好。

  • 缓存返回值

装饰器可以为缓存和备忘提供一个很好的机制。作为一个例子,让我们看一下斐波那契数列的递归定义:

import functools
from decorators import count_calls

def cache(func):
    """Keep a cache of previous function calls"""
    @functools.wraps(func)
    def wrapper_cache(*args, **kwargs):
        cache_key = args + tuple(kwargs.items())
        if cache_key not in wrapper_cache.cache:
            wrapper_cache.cache[cache_key] = func(*args, **kwargs)
        return wrapper_cache.cache[cache_key]
    wrapper_cache.cache = dict()
    return wrapper_cache

@cache
@count_calls
def fibonacci(num):
    if num < 2:
        return num
    return fibonacci(num - 1) + fibonacci(num - 2)

在标准库中,最近使用最少的缓存(LRU)可作为 @functools.lru_cache。

这个装饰器比你上面看到的那个有更多的功能。你应该使用@functools.lru_cache而不是写你自己的缓存装饰器:

import functools

@functools.lru_cache(maxsize=4)
def fibonacci(num):
    print(f"Calculating fibonacci({num})")
    if num < 2:
        return num
    return fibonacci(num - 1) + fibonacci(num - 2)

maxsize参数指定了多少个最近的调用被缓存。默认值是128,但你可以指定maxsize=None来缓存所有函数调用。然而,要注意的是,如果你要缓存许多大的对象,这可能会导致内存问题。

描述器descriptor

任何定义了 __get__()__set__() 或 __delete__() 方法的对象。当类属性为描述器时,它的特殊绑定行为就会在属性查找时被触发。通常情况下,使用 a.b 来获取、设置或删除属性时会在 a 的类字典中查找名称为 b 的对象,但如果 b 是描述器,则会调用对应的描述器方法。理解描述器的概念是更深层次理解 Python 的关键,因为这是许多重要特性的基础,包括函数、方法、属性、类方法、静态方法以及对超类的引用等等。

有关描述符的方法的详情可参看 实现描述器。

class property(fget=None, fset=None, fdel=None, doc=None)

fget 是获取属性值的函数。 fset 是用于设置属性值的函数。 fdel 是用于删除属性值的函数。并且 doc 为属性对象创建文档字符串。

class C():
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")
    
demo = C()
demo.x = 5
print(demo.x)
print(demo.getx())

执行结果文章来源地址https://www.toymoban.com/news/detail-499893.html

5
5

更快捷的方式:

class C():
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x
    
demo = C()
demo.x = 5
print(demo.x)

@property 装饰器会将 x() 方法转化为同名的只读属性的 "getter",并将 x的文档字符串设置为 "I'm the 'x' property."

执行结果

5

到了这里,关于python测试开发面试常考题:装饰器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • IC面试常考题 Verilog三分频电路设计(占空比50%,三分之一,三分之二)

    实现三分频电路最简单的是: 利用计数器实现。 时序图分析(本人比较懒,平常科研忙,所以直接手画时序图了,懒得用软件画了): 直接上图分析:利用计数器每隔三个周期信号翻转一次,同时在不同的计数下翻转得到的同步信号 clk_1和clk_2,再利用异或即可实现出一个

    2024年02月16日
    浏览(9)
  • Soft:软件开发的简介(敏捷开发等6大软件开发模式)、软件测试的简介(单元测试/集成测试/系统测试/验收测试/回归测试、黑白灰功能测试、DEV等四套环境)、运维的简介之详细攻略

    Soft:软件开发的简介(敏捷开发等6大软件开发模式)、软件测试的简介(单元测试/集成测试/系统测试/验收测试/回归测试、黑白灰功能测试、DEV等四套环境)、运维的简介之详细攻略 目录 1、软件开发(敏捷开发等6大软件开发模式) Computer:敏捷开发Scrum方法的简介、发展历程、开

    2024年02月04日
    浏览(18)
  • 装饰器模式简介

    装饰器模式( Decorator Pattern )是一种结构型设计模式,允许您在不改变现有对象结构的情况下,动态地将新功能附加到对象上。通过创建一个包装器类来扩展原始类的功能。这个包装器类具有与原始类相同的接口,并在内部持有一个指向原始对象的引用。通过将多个包装器链

    2024年02月10日
    浏览(8)
  • 测试开发之前端篇-Web前端简介

    自从九十年代初,人类创造出网页和浏览器后,Web取得了长足的发展,如今越来越多的企业级应用也选择使用Web技术来构建。 前面给大家介绍网络协议时讲到,您在阅读这篇文章时,浏览器是通过HTTP/HTTPS协议向服务器发送请求、并显示了其响应内容的。本文给大家简要介绍

    2024年02月13日
    浏览(15)
  • 百度 测试|测试开发 面试真题|面经 汇总

    事业群:MEG base:北京 一面:2022.8.12 时长:50min 自我介绍 个人项目,我的项目是围绕着学校课程的项目来的,面试官就让我介绍这门课讲了些什么 (学校里)性能测试做了什么工作,性能测试中需要关注什么部分,我从前端和后端分开来讲的 接口测试关注的部分 实习中做

    2024年02月10日
    浏览(9)
  • 百度测试开发工程师面试心得

       电话面试:    面试官:首先做一下自我介绍吧    我:我是***,来自什么大学,现在大三,在学校期间担任过部长,副主席等职务,           组织举办了很多比赛,例如校园篮球比赛,校园迎新晚会、校园创业大赛等,           我平时爱运动健身,偶尔和同学

    2024年02月07日
    浏览(14)
  • 测试开发面试宝典,涨价倒计时

    大家好,我是洋子,相信在面试软件测试、测试开发岗位的小伙伴都深有体会,考察的知识点越来越多 不仅会考察到软件测试的理论,让你对某种功能进行测试用例的设计,更难一点会给出一个 测试场景 进行测试方案的设计,现如今有的公司在面试时,甚至还会问到接口测

    2024年02月05日
    浏览(26)
  • 金九银十面试怒拿6个offer——测试开发面试题整理

    金九银十面试怒拿6个offer——测试开发面试题整理 1、软件测试的流程是什么? 2、测试用例主要有哪些元素? 3、软件测试有什么策略和阶段? 4、黑盒测试和白盒测试是什么?二者有什么区别? 5、软件测试有什么类型? 6、测试用例是什么?有什么作用? 7、你平时是怎么

    2023年04月08日
    浏览(9)
  • 吊打面试官系列之:常见测试开发面试题汇总,在面试的路上,总要先下手为强。

    自我介绍; 介绍下你参与的公司项目; 你有什么优点

    2024年02月15日
    浏览(12)
  • Python简介及开发环境搭建

    Python是一种跨平台的计算机程序设计语言,将用户的想法传达给Python,它再以计算机所认识的方式告诉计算机,它充当着用户与计算机之间交流的工具;它是一种解释型语言,在开发的过程中没有编译这个环节,在这一点上它与Java不一样;它是一种面向对象的语言,在它的世

    2024年02月13日
    浏览(19)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包