python装饰器property和setter用法
作者:wx62cea850b9e28??????? 发布时间:2023-02-14 09:01:05
标签:python,装饰器,property,setter,用法
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)
来源:https://blog.51cto.com/u_15717393/5470902
0
投稿
猜你喜欢
- 1.python 和 pytorch的数据类型区别在PyTorch中无法展示字符串,因此表达字符串,需要将其转换成编码的类型,比如one_h
- 作为语言模型和文本挖掘中的常用工具,Word2Vec也可以用来构建聊天机器人。在本文中,我们将使用Python和Gensim库从头开始构建一
- 转自微信公众号: Python之禅1.日志简介说到日志,无论是写框架代码还是业务代码,都离不开日志的记录,他能给我们定位问题带来极
- python-opencv获取二值图像轮廓及中心点坐标代码:groundtruth = cv2.imread(groundtruth_pat
- 今天要用python做一个小功能,那就是实现万年历的查询。首先看一下整体感觉实现代码:def is_leap_year(year): &nb
- 今天修改之前实习小伙伴写的js代码的时候,遇到修改后页面未发生变化的问题。因为我是web开发小白,所以上网查了一波,得以解决~~初次进行we
- 说到转置操作,顺便提及矩阵与数组的区别:矩阵:数学里的概念,其元素只能是数值,这也是区别于数组的根本所在数组:计算机中的概念,代表一种数据组
- 这篇文章主要介绍了python集合删除多种方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可
- 一个简单但功能比较完善的自动生成缩略图的函数,可以按需要对图片进行缩放、裁切、锁定宽或高、使用空白填充以下为源码,比较简单,相信很容易看明白
- 喜欢用 Python 做项目的小伙伴不免会遇到这种情况:做图表时,用哪种好看又实用的可视化工具包呢?之前文章里出现过漂亮的图表时,也总有读者
- 在python中使用open函数对文件进行处理。1.open()python打开文件使用open()函数,返回一个指向文件的指针。该函数常用
- 在python中利用numpy创建一个array, 然后我们想获取array的最大值,最小值。可以使用一下方法:一、创建数组这样就可以获得一
- 因为 GAE 在国内访问不便,所以平时有一些小应用,我都会放在 SAE 上面, 虽然 SAE 还有很多缺陷,但算是上手比较容易的一个了,最起
- 问题:自己写了个dataloader,为了部署方便,用OpenCV的接口进行数据读取,而没有用PIL,代码大致如下: &nbs
- 一、现状Python 有诸多优秀的 Web 开发框架供我们使用,比如Django、Flask、Sanic。正常的情况下,我们基于这些 Web
- 第一列按照goodsid局部分组,然后在分组后的记录中按照audittime升序排序得到序号,从而显示某商品得第几次变迁。 第二列是取该商品
- 1.writelines()直接写入l=["A","B","C","D
- 排序算法是《数据结构与算法》中最基本的算法之一,也是面试必背题,为方便技术交流,文末创建技术交流群。排序算法可以分为内部排序和外部排序,内部
- 1. 加载数据集这次我们搭建一个小小的多层线性网络对糖尿病的病例进行分类首先先导入需要的库文件先来看看我们的数据集观察可以发现,前八列是我们
- 引言做接口测试中,对于一般性的单业务接口测试很多工具可供选择,但是对于一些相关业务相关性的关联接口测试就比较麻烦,使用工具比如jmeter、