美文网首页
Python @property 详解

Python @property 详解

作者: Double_E | 来源:发表于2017-03-29 20:36 被阅读236次
  • 类方法转为只读属性

  • 重新实现属性的setter, getter, deleter方法

类方法转为只读属性

class Jhy(object):
    """docstring for Jhy"""
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def all(self):
        return ('a: {}, b: {}'.format(self.a, self.b))
    @property
    def all2(self):
        return('a: {}, b: {}'.format(self.a, self.b))
    

if __name__ == '__main__':
    jhy = Jhy('name1', 'name2')
    print(jhy.all()) #方法调用有()
    print(jhy.all2) #属性调用没()
    jhy.all2 = 11 # 这个属性赋值会报错

输出:
a: name1, b: name2
a: name1, b: name2
jhy.all2 = 11 AttributeError: can't set attribute

property代替 setter和getter, deleter方法, 类方法转为可修改属性

class Jhy(object):
    """docstring for Jhy"""


    @property
    def all(self):
        return self._all

    @all.setter #  设置属性修改方法 ,这里all = property(all)
    def all(self, a):
        if a != 1:
            self._all = a 
        else:
            print('Need a != 1')

    @all.deleter
    def all(self):
        del self._all
        pass



    

if __name__ == '__main__':
    jhy = Jhy()
    jhy.all = 11
    print(jhy.all) # 输出11
    del jhy.all
    print(jhy.all) # 报错 因为已经删除了
 输出:
11
Traceback (most recent call last):
  File "C:\Users\jhy\Desktop\Tensorflow Demo\2.py", line 36, in <module>
    print(jhy.all)
  File "C:\Users\jhy\Desktop\Tensorflow Demo\2.py", line 14, in all
    return self._all
AttributeError: 'Jhy' object has no attribute '_all

实例

tensorflow/python/ops/control_flow_ops.py

Paste_Image.png

相关文章

  • python @property

    参考 Python进阶之“属性(property)”详解 - Python - 伯乐在线

  • Python @property 详解

    类方法转为只读属性 重新实现属性的setter, getter, deleter方法 类方法转为只读属性 pro...

  • Python @property 详解

    一、概述 python中 @property 是python的一种装饰器,是用来修饰方法的。我们可以使用@pro...

  • python --@property装饰器详解

    既要保护类的封装特性,又要让开发者可以使用“对象.属性”的方式操作操作类属性,除了使用 property() 函数...

  • iOS开发---属性关键字详解

    iOS开发—属性关键字详解 @Property 什么是属性? 属性(property)是Objective-C的一...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • 25.Python编程:@property详解

    在前面学习访问权限一文中,我们设计了一个SmartPhone类, 如果你观察的足够仔细,你会发现,例子中我们属性只...

  • 详解python当中的@property对象

    python当中有个概念叫property,这个概念或者说模块我们经常用到,但是这个到底是什么,可能比较少谈论这个...

  • 2018-02-05

    python @property装饰器

  • python元编程详解

    注:采转归档,自己学习查询使用 python元编程详解(1)python元编程详解(2)python元编程详解(3...

网友评论

      本文标题:Python @property 详解

      本文链接:https://www.haomeiwen.com/subject/cfyyottx.html