python3中的property有一个很有意思的功能,它能将类中的方法像类属性一样调用!

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

我们先来简单了解一下这个property类,下面看一下官网给出的例子:

class C:def __init__(self):self._x = Nonedef getx(self):return self._xdef setx(self, value):self._x = valuedef delx(self):del self._xx = property(getx, setx, delx, "I'm the 'x' property.")  # 这里的x相当于类属性c = C()  # 生成一个对象
c.x = 10  # 设置self._x=10,实际调用的就是类中setx方法
c.x  # 获取self._x的值,实际调用的就是类中getx方法
del c.x  # 删除self._x的值,实际调用的就是类中delx方法

是不是感觉很有意思,很不可思议!property中fget是一个函数,它获取属性值;fset是一个函数,它设置一个属性值;fdel是一个函数,它删除一个属性值;doc为该属性创建一个docstring。你只要在使用时在对应的形参位置放上你写的对应函数,就可以轻松使用了。

我们还可以将property作为装饰器来使用,还是使用官网的例子:

class C:def __init__(self):self._x = None@propertydef x(self):"""I'm the 'x' property."""return self._x@x.setterdef x(self, value):self._x = value@x.deleterdef x(self):del self._x

property对象有getter、setter、deleter三个方法,getter获取属性值,setter设置属性值,deleter设置属性值,这个例子的效果跟上一个例子的效果完全相同!我们看到里面的方法名是一模一样的,但是达到的效果却是不同的。第一个x方法是获取属性值,第二个x方法是设置属性值,第三个x方法是删除属性值。

你看到这里是不是以为这一切都是property帮你做到的,错,错,错!其实property只做了一件事件,它将你的方法能像类属性一样使用,至于里面的查、删、改,其实都是你自己写的函数实现的!fget、fset、fdel、setter、deleter这些仅仅只是名字而且,方便你识别,其他什么作用都没有!

我们来看一下property的源代码:

class property(object):"""property(fget=None, fset=None, fdel=None, doc=None) -> property attributefget is a function to be used for getting an attribute value, and likewisefset is a function for setting, and fdel a function for del'ing, anattribute.  Typical use is to define a managed attribute x:class C(object):def getx(self): return self._xdef setx(self, value): self._x = valuedef delx(self): del self._xx = property(getx, setx, delx, "I'm the 'x' property.")Decorators make defining new properties or modifying existing ones easy:class C(object):@propertydef x(self):"I am the 'x' property."return self._x@x.setterdef x(self, value):self._x = value@x.deleterdef x(self):del self._x"""def deleter(self, *args, **kwargs): # real signature unknown""" Descriptor to change the deleter on a property. """passdef getter(self, *args, **kwargs): # real signature unknown""" Descriptor to change the getter on a property. """passdef setter(self, *args, **kwargs): # real signature unknown""" Descriptor to change the setter on a property. """passdef __delete__(self, *args, **kwargs): # real signature unknown""" Delete an attribute of instance. """passdef __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __get__(self, *args, **kwargs): # real signature unknown""" Return an attribute of instance, which is of type owner. """passdef __init__(self, fget=None, fset=None, fdel=None, doc=None): # known special case of property.__init__"""property(fget=None, fset=None, fdel=None, doc=None) -> property attributefget is a function to be used for getting an attribute value, and likewisefset is a function for setting, and fdel a function for del'ing, anattribute.  Typical use is to define a managed attribute x:class C(object):def getx(self): return self._xdef setx(self, value): self._x = valuedef delx(self): del self._xx = property(getx, setx, delx, "I'm the 'x' property.")Decorators make defining new properties or modifying existing ones easy:class C(object):@propertydef x(self):"I am the 'x' property."return self._x@x.setterdef x(self, value):self._x = value@x.deleterdef x(self):del self._x# (copied from class doc)"""pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __set__(self, *args, **kwargs): # real signature unknown""" Set an attribute of instance to value. """passfdel = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultfget = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultfset = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default__isabstractmethod__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

看到上面的源代码恍然大悟没,fdel、fget、fset都只是执行你函数里面的代码而已!所以我们就记住一句话就够了:“property能让你的方法像类属性一样使用”。

转载于:https://blog.51cto.com/daibaiyang119/1972460

Python3 property属性相关推荐

  1. 定义一个属性_Python property属性

    1. 什么是property属性 一种用起来像是使用的实例属性一样的特殊属性,可以对应于某个方法 # ############### 定义 ###############class Foo: def ...

  2. Python中菱形继承的MRO顺序及property属性

    Python中菱形继承的MRO顺序及property属性 文章目录 Python中菱形继承的MRO顺序及property属性 一.Python中菱形继承的MRO顺序 1. 单独调用父类的方法 2. 多 ...

  3. python中的property_python中的property属性

    1. 什么是property属性 一种用起来像是使用的实例属性一样的特殊属性,可以对应于某个方法 # ############### 定义 ############### class Foo: def ...

  4. python提高——多继承、静态方法、类方法、property属性、魔法属性

    目录 1多继承 单独调用父类得方法 多继承中super调用父类的被重写的方法 单继承中super 2静态方法.类方法 2.1类属性.实例属性 2.2实例方法.静态方法和类方法 3property属性 ...

  5. 论 静态方法@staticmethod 类方法@classmethod @property属性

    1. 类属性.实例属性 class Province(object):# 类属性country = '中国'def __init__(self, name):# 实例属性self.name = nam ...

  6. property属性的使用

    property的作用是将一个属性的操作方法封装为一个属性,用户使用起来就和操作普通属性完全一致. property属性有两种使用方式: 装饰器 :在方法上应用装饰器 类属性:在类中定义值为prope ...

  7. 类 property属性

    类的定义 类的创建: 类是通过属性来保存数据的. 成员变量的修饰: Private:私有 外部不可访问 不可继承 Protected:被保护 外部不可访问 可继承 Public:公共 可被外部访问 可 ...

  8. python 基础教程:对 property 属性的讲解及用法

    Python中property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回 property属性的有两种方式: 装饰器 即:在方法上应用装饰器 类属性 即:在类中定义 ...

  9. python 中 property 属性的讲解及应用

    Python中property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回 property属性的有两种方式: 装饰器 即:在方法上应用装饰器 类属性 即:在类中定义 ...

最新文章

  1. 深度神经网络混合精度训练
  2. 码农技术炒股之路——任务管理器
  3. 对信号与系统课程的意见与建议
  4. linux c 通过 pid 获取 进程相关信息 cmdline
  5. go语言基础到提高(7)-数组
  6. linux命令画圣诞树图片,以 Linux 的方式庆祝圣诞节
  7. 信息学奥赛C++语言:与 7 无关的数的个数
  8. Ubuntu sudo 出现unable to resolve host 解决方法
  9. java第十四次作业
  10. c++两数组合并算法
  11. 粒子滤波简介(转载)
  12. html图书馆占座系统,图书馆选座系统,再也不用担心有人占座啦!
  13. 解决:cannot deserialize from Object value (no delegate- or property-based Creator)
  14. mtex极图_一种多相金属材料相成分识别的方法与流程
  15. Html5餐饮管理app,哗啦啦餐饮软件 餐饮管理系统
  16. 腾讯6W月薪架构师能力曝光!微信架构为什么是史上最值钱的IM架构?
  17. Github13K!相似搜索百宝箱,文本匹配入门必备!
  18. 在Centos7上安装vpnc客户端
  19. 好分数一个等第是什么意思_DPI是什么意思 鼠标DPI越高越好吗?
  20. html钟表代码运行原理,·钟表指针运行方向的基本原理

热门文章

  1. Dubbo暴露服务过程
  2. css控制边界与边框示例(内边距、外边距使用方法)
  3. c语言考试长沙理工大学,2013年长沙理工大学C语言考试试卷A.doc
  4. mysql 秀出两个相关联的表中满足条件的内容_这六个 MySQL 死锁案例,能让你理解死锁的原因!...
  5. python的全局变量能暂存数据吗_Python 中的全局变量 局部变量
  6. cubemx lan8720a ping不通_肩颈不通百病生,这5个开肩动作要多练
  7. 利用nodeJs anywhere搭建本地服务器环境
  8. 计算机控制实验教程,新)《计算机控制技术》实验教程.doc
  9. 计算机软件硬件试讲,试讲:初识计算机网络
  10. 第五天2017/04/06(下午1:C、C++混合编程 与 #ifdef __cplusplus extern C{ })