python装饰器property和setter用法

目录
  • 1.引子:函数也是对象
  • 2.函数内的函数
  • 3.装饰器小栗子
  • 5.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)

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

(0)

相关推荐

  • python中property和setter装饰器用法

    作用:调用方法改为调用对象, 比如 : p.set_name() 改为 p.set_name 区别:前者改变get方法,后者改变set方法 效果图: 代码: class Person: def __init__(self,name): self._name = name def get_name(self): return self._name def set_name(self,name): self._name = name p = Person('小黑') print(p.get_name

  • python中@property的作用和getter setter的解释

    @property作用: python的@property是python的一种装饰器,是用来修饰方法的. 我们可以使用@property装饰器来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性,可以与所定义的属性配合使用,这样可以防止属性被修改. 1.修饰方法,让方法可以像属性一样访问. class DataSet(object): @property def method_with_property(self): ##含有@property return 15 def m

  • Python @property及getter setter原理详解

    @property作用: python的@property是python的一种装饰器,是用来修饰方法的. 我们可以使用@property装饰器来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性,可以与所定义的属性配合使用,这样可以防止属性被修改. 1.修饰方法,让方法可以像属性一样访问. class DataSet(object): @property def method_with_property(self): ##含有@property return 15 def m

  • Python如何使用@property @x.setter及@x.deleter

    @property可以将python定义的函数"当做"属性访问,从而提供更加友好访问方式,但是有时候setter/deleter也是需要的. 只有@property表示只读. 同时有@property和@x.setter表示可读可写. 同时有@property和@x.setter和@x.deleter表示可读可写可删除. 代码如下 class student(object): #新式类 def __init__(self,id): self.__id=id @property #读 d

  • python装饰器property和setter用法

    目录 1.引子:函数也是对象 2.函数内的函数 3.装饰器小栗子 5.property和setter用法 1.引子:函数也是对象 木有括号的函数那就不是在调用. def hi(name="yasoob"): return "hi " + name print(hi()) # output: 'hi yasoob' # 我们甚至可以将一个函数赋值给一个变量,比如 greet = hi # 我们这里没有在使用小括号,因为我们并不是在调用hi函数 # 而是在将它放在gre

  • Python装饰器(decorator)定义与用法详解

    本文实例讲述了Python装饰器(decorator)定义与用法.分享给大家供大家参考,具体如下: 什么是装饰器(decorator) 简单来说,可以把装饰器理解为一个包装函数的函数,它一般将传入的函数或者是类做一定的处理,返回修改之后的对象.所以,我们能够在不修改原函数的基础上,在执行原函数前后执行别的代码.比较常用的场景有日志插入,事务处理等. 装饰器 最简单的函数,返回两个数的和 def calc_add(a, b): return a + b calc_add(1, 2) 但是现在又有新

  • Python装饰器基础概念与用法详解

    本文实例讲述了Python装饰器基础概念与用法.分享给大家供大家参考,具体如下: 装饰器基础 前面快速介绍了装饰器的语法,在这里,我们将深入装饰器内部工作机制,更详细更系统地介绍装饰器的内容,并学习自己编写新的装饰器的更多高级语法. 什么是装饰器 装饰是为函数和类指定管理代码的一种方式.Python装饰器以两种形式呈现: [1]函数装饰器在函数定义的时候进行名称重绑定,提供一个逻辑层来管理函数和方法或随后对它们的调用. [2]类装饰器在类定义的时候进行名称重绑定,提供一个逻辑层来管理类,或管理随

  • Python装饰器原理与简单用法实例分析

    本文实例讲述了Python装饰器原理与简单用法.分享给大家供大家参考,具体如下: 今天整理装饰器,内嵌的装饰器.让装饰器带参数等多种形式,非常复杂,让人头疼不已.但是突然间发现了装饰器的奥秘,原来如此简单.... 第一步 :从最简单的例子开始 # -*- coding:gbk -*- '''示例1: 使用语法糖@来装饰函数,相当于"myfunc = deco(myfunc)" 但发现新函数只在第一次被调用,且原函数多调用了一次''' def deco(func): print(&quo

  • Python装饰器模式定义与用法分析

    本文实例讲述了Python装饰器模式定义与用法.分享给大家供大家参考,具体如下: 装饰器模式定义:动态地给一个对象添加一些额外的职责. 在Python中Decorator mode可以按照像其它编程语言如C++, Java等的样子来实现,但是Python在应用装饰概念方面的能力上远不止于此,Python提供了一个语法和一个编程特性来加强这方面的功能. 首先需要了解一下Python中闭包的概念:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(c

  • Python装饰器原理与基本用法分析

    本文实例讲述了Python装饰器原理与基本用法.分享给大家供大家参考,具体如下: 装饰器: 意义:在不能改变原函数的源代码,和在不改变整个项目中原函数的调用方式的情况下,给函数添加新的功能 由于不允许改变函数的源代码,在忽略调用方式的情况下,我们可能会有以下结果: def decorator(func): func() print("logging") def test1(): print("test1") def test2(): print("Test

  • Python装饰器原理与用法分析

    本文实例讲述了Python装饰器原理与用法.分享给大家供大家参考,具体如下: 1.装饰器的本质是函数,主要用来装饰其他函数,也就是为其他函数添加附加功能 2.装饰器的原则: (1) 装饰器不能修改被装饰的函数的源代码 (2) 装饰器不能修改被装饰的函数的调用方式 3.实现装饰器的知识储备 (1) Python中函数即'变量' a.变量在Python中的存储 x='Tomwenxing' y=x [说明]: 当Python解释器遇到语句x='Tomwenxing'时,它主要完成了两样工作: 1.在

  • 无惧面试,带你搞懂python 装饰器

    写在之前 「装饰器」作为 Python 高级语言特性中的重要部分,是修改函数的一种超级便捷的方式,适当使用能够有效提高代码的可读性和可维护性,非常的便利灵活. 「装饰器」本质上就是一个函数,这个函数的特点是可以接受其它的函数当作它的参数,并将其替换成一个新的函数(即返回给另一个函数). 可能现在这么看的话有点懵,为了深入理解「装饰器」的原理,我们首先先要搞明白「什么是函数对象」,「什么是嵌套函数」,「什么是闭包」.关于这三个问题我在很久以前的文章中已经写过了,你只需要点击下面的链接去看就好了,这

  • python3 property装饰器实现原理与用法示例

    本文实例讲述了python3 property装饰器实现原理与用法.分享给大家供大家参考,具体如下: 学习python的同学,慢慢的都会接触到装饰器,装饰器在python里是功能强大的语法.装饰器配合python的魔法方法,能实现很多意想不到的功能.废话不多说,如果你已经掌握了闭包的原理,代码的逻辑还是可以看明白的,咱们直接进入正题. property的意义 @property把一个类的getter方法变成属性,如果还有setter方法,就在setter方法前面加上@method.setter.

  • Python装饰器中@property使用详解

    目录 最初的声明方式 使用装饰器的声明方式 使用装饰器的调用过程 总结 最初的声明方式 在没有@property修饰的情况下,需要分别声明get.set.delete函数,然后初始化property类,将这些方法加载进property中 class C持有property的实例化对象x 对外表现出来C().x时,实际上是调用C()中的x(property类)中设置的fset,fget,fdel,分别对应getx,setx,delx C真正持有的x,是self._x被隐藏起来了 class C(o

随机推荐