iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python装饰器property和setter用法
  • 261
分享到

python装饰器property和setter用法

2024-04-02 19:04:59 261人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录1.引子:函数也是对象2.函数内的函数3.装饰器小栗子5.property和setter用法1.引子:函数也是对象 木有括号的函数那就不是在调用。 def hi(name="ya

1.引子:函数也是对象

木有括号的函数那就不是在调用。

def hi(name="yasoob"):
return "hi " + name
print(hi())
# output: 'hi yasoob'
# 我们甚至可以将一个函数赋值给一个变量,比如
greet = hi
# 我们这里没有在使用小括号,因为我们并不是在调用hi函数
# 而是在将它放在greet变量里头。我们尝试运行下这个
print(greet())
# output: 'hi yasoob'
# 如果我们删掉旧的hi函数,看看会发生什么!
del hi
print(hi())
#outputs: NameError
print(greet())
#outputs: 'hi yasoob'

2.函数内的函数

(1)在python中,一个函数内能嵌套定义另一个函数,并且可以在该大函数内调用该小函数。

def hi(name="yasoob"):
print("now you are inside the hi() function")

def greet():
return "now you are in the greet() function"

def welcome():
return "now you are in the welcome() function"

print(greet())
print(welcome())
print("now you are back in the hi() function")

hi()
#output:now you are inside the hi() function
# now you are in the greet() function
# now you are in the welcome() function
# now you are back in the hi() function

# 上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用。
# 然后greet()和welcome()函数在hi()函数之外是不能访问的,比如:
greet()
#outputs: NameError: name 'greet' is not defined

(2)开始神奇的是,大函数的返回值可以是一个函数:

def hi(name="yasoob"):
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
if name == "yasoob":
return greet #这里!!
else:
return welcome
a = hi()
print(a)
#outputs: <function greet at 0x7f2143c01500>
#上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
#现在试试这个
print(a())
#outputs: now you are in the greet() function

在 if/else 语句中我们返回 greet 和 welcome,而不是 greet() 和 welcome()。
为什么那样?这是因为当你把一对小括号放在后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。

当我们写下 a = hi(),hi() 会被执行,而由于 name 参数默认是 yasoob,所以函数 greet 被返回了。

PS:如果我们打印出 hi()(),这会输出 now you are in the greet() function。

(3)最后要说的是函数作为参数传入一个函数:

def hi():
return "hi yasoob!"
def doSomethingBeforeHi(func):
print("I am doing some boring work before executing hi()")
print(func())
doSomethingBeforeHi(hi)
#outputs:I am doing some boring work before executing hi()
# hi yasoob!

3.装饰器小栗子

终于来到了带@的装饰器,其实就是带了@帽子的函数作为参数,传入@后面的函数中。

def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
"""Hey you! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")

a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

上面的代码等价于我们熟悉的:

def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction

def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")

a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()

不过一开始上面被装饰过的函数名字已经悄悄发生“改变”,如果print下可以看出(如下代码)。
解决方案:
@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。

print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction

最终加上@wraps的代码如下:

from functools import wraps
def a_new_decorator(a_func):
@wraps(a_func)
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
"""Hey yo! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration

5.property和setter用法

class Timer:
def __init__(self, value = 0.0):
self._time = value
self._unit = 's'
# 使用装饰器的时候,需要注意:
# 1. 装饰器名,函数名需要一直
# 2. property需要先声明,再写setter,顺序不能倒过来
@property
def time(self):
return str(self._time) + ' ' + self._unit
@time.setter
def time(self, value):
if(value < 0):
raise ValueError('Time cannot be negetive.')
self._time = value
t = Timer()
t.time = 1.0
print(t.time)

到此这篇关于Python装饰器property和setter用法的文章就介绍到这了,更多相关python property与setter内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: python装饰器property和setter用法

本文链接: https://www.lsjlt.com/news/119425.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python装饰器property和setter用法
    目录1.引子:函数也是对象2.函数内的函数3.装饰器小栗子5.property和setter用法1.引子:函数也是对象 木有括号的函数那就不是在调用。 def hi(name="ya...
    99+
    2024-04-02
  • python装饰器property和setter怎么使用
    本篇内容介绍了“python装饰器property和setter怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1.引子:函数也是对象...
    99+
    2023-07-02
  • python @property 装饰器使用方法
    目录一、property的装饰器用法二、举例说明1.不用setter和getter方法的实现2.使用setter和getter的实现,增加温度值输入的限制3.利用property装饰...
    99+
    2024-04-02
  • python中property装饰器的使用方法
    这篇文章主要介绍python中property装饰器的使用方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!python的数据类型有哪些python的数据类型:1. 数字类型,包括int(整型)、long(长整型)和...
    99+
    2023-06-15
  • python中@property装饰器怎么用
    这篇文章主要介绍python中@property装饰器怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!一、property的装饰器用法先简单上个小栗子说明:class property(fget=None,fse...
    99+
    2023-06-29
  • Python装饰器中@property使用详解
    目录最初的声明方式使用装饰器的声明方式使用装饰器的调用过程总结最初的声明方式 在没有@property修饰的情况下,需要分别声明get、set、delete函数,然后初始化prope...
    99+
    2024-04-02
  • Python property装饰器使用案例介绍
    目录1.property2.property属性定义的两种方式3.案例1.property 装饰器:装饰器是在不修改被装饰对象源代码以及调用方式的前提下为被装饰对象添加新功能的可调用...
    99+
    2024-04-02
  • 如何在Python中使用@property装饰器
    这期内容当中小编将会给大家带来有关如何在Python中使用@property装饰器,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。一、property() 函数讲解了解 @property 装饰器之前,我们...
    99+
    2023-06-15
  • Python Property装饰器的作用是什么
    本篇内容介绍了“Python Property装饰器的作用是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1. property装饰器的...
    99+
    2023-06-15
  • Python深入分析@property装饰器的应用
    目录什么是propertyproperty属性定义的两种方式@property属性值的限制什么是property 简单地说就是一个类里面的方法一旦被@property装饰,就可以像调...
    99+
    2024-04-02
  • 怎么使用@Staticmethod、@Classmethod和@Property类装饰器
    这篇文章主要讲解了“怎么使用@Staticmethod、@Classmethod和@Property类装饰器”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用@Staticmethod、...
    99+
    2023-06-15
  • python知识:装饰器@property到底有啥用途
    目录一、提要二、关于属性的约定2.1 类绑定属性2.2 对象绑定属性2.3 私有属性 三、应用@property装饰器3.1 将一个属性转成方法3.2 私有化某些属性3.3...
    99+
    2023-01-04
    python装饰器 python @property python知识
  • python中装饰器的用法
    这篇文章主要介绍python中装饰器的用法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!一、装饰器使用场景经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳...
    99+
    2023-06-15
  • python装饰器2:类装饰器
    装饰器1:函数装饰器 装饰器2:类装饰器 装饰器3:进阶 本文是装饰器相关内容的第二篇,关于类装饰器。 "类装饰器"有两种解读方式:用来装饰类的装饰器;类作为装饰器装饰其它东西。你如何认为取决于你,两种说法都有出现在其它的文章中。我的...
    99+
    2023-01-30
    python
  • Python 语法之装饰器
      装饰器的概念  装饰器是 Python 的一个重要部分。简单地说:就是用于拓展原来函数功能的一种函数,目的是在不改变原函数名(或类名)的情况下,给函数增加新的功能。  这个函数的特殊之处在于它的返回值也是一个函数,这个函数是内嵌 “原”...
    99+
    2023-06-02
  • python装饰器
    什么是装饰器:   装饰器就是python中的一个语法糖。作用就是在不改动之前代码的情况下给某个函数增加相应想要增加的功能。 假设需求:   我在几个函数内分别放了一部电影,代码如下: 1 def mv1(): 2 print(...
    99+
    2023-01-30
    python
  • python-装饰器
    装饰器简介:给被装饰的函数在不更改代码的基础上增加新的功能;多个装饰器的执行顺序:从最靠近原始函数的装饰器开始执行,最后执行原始函数; 直接上个简单的例子就懂了: 一 最简单的装饰器:#!/usr/bin/python def deco(f...
    99+
    2023-01-31
    python
  • python装饰器的定义及用法
    本篇内容主要讲解“python装饰器的定义及用法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“python装饰器的定义及用法”吧!  定义:  本质是函数(装饰其他函数),就是为其他函数添加附加...
    99+
    2023-06-02
  • python 装饰器
    装饰器本质上是一个Python函数,它可以让其他函数在不雲要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面雲求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳...
    99+
    2023-01-30
    python
  • python @property用法作用
    @property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。详见链接:廖雪峰python3使用@property练习请利用@property给一个Screen对象加...
    99+
    2023-01-31
    作用 python property
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作