zoukankan      html  css  js  c++  java
  • python---property属性

    @property 可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/getter也是需要的

    假设定义了一个类Cls,该类必须继承自object类,有一私有变量__x

    1. 第一种使用属性的方法:

    [python] view plain copy
     print?
    1. #!/usr/bin/env python  
    2. # -*- coding: utf-8 -*-  
    3. # blog.ithomer.net  
    4.   
    5. class Cls(object):  
    6.     def __init__(self):  
    7.         self.__x = None  
    8.       
    9.     def getx(self):  
    10.         return self.__x  
    11.       
    12.     def setx(self, value):  
    13.         self.__x = value  
    14.           
    15.     def delx(self):  
    16.         del self.__x  
    17.           
    18.     x = property(getx, setx, delx, 'set x property')  
    19.   
    20. if __name__ == '__main__':  
    21.     c = Cls()  
    22.     c.x = 100  
    23.     y = c.x  
    24.     print("set & get y: %d" % y)  
    25.       
    26.     del c.x  
    27.     print("del c.x & y: %d" % y)     
    运行结果:

    set & get y: 100
    del c.x & y: 100

    在该类中定义三个函数,分别用作赋值、取值、删除变量

    property函数原型为property(fget=None,fset=None,fdel=None,doc=None),上例根据自己定义相应的函数赋值即可。


    2. 第二种方法(在2.6中新增)
    同方法一,首先定义一个类Cls,该类必须继承自object类,有一私有变量__x

    [python] view plain copy
     print?
    1. class Cls(object):  
    2.     def __init__(self):  
    3.         self.__x = None  
    4.          
    5.     @property  
    6.     def x(self):  
    7.         return self.__x  
    8.      
    9.     @x.setter  
    10.     def x(self, value):  
    11.         self.__x = value  
    12.          
    13.     @x.deleter  
    14.     def x(self):  
    15.         del self.__x  
    16.   
    17. if __name__ == '__main__':  
    18.     c = Cls()  
    19.     c.x = 100  
    20.     y = c.x  
    21.     print("set & get y: %d" % y)  
    22.       
    23.     del c.x  
    24.     print("del c.x & y: %d" % y)   
    运行结果:
    set & get y: 100
    del c.x & y: 100
    说明: 同一属性__x的三个函数名要相同。



    参考推荐:

    python Property属性用法

    python学习笔记 - @property

    关注公众号 海量干货等你
  • 相关阅读:
    spring reference
    Connector for Python
    LDAP
    REST
    java利用泛型实现不同类型可变参数
    java细节知识
    事务隔离的级别
    servlet cdi注入
    session and cookie简析
    CORS’s source, principle and implementation
  • 原文地址:https://www.cnblogs.com/sowhat1412/p/12734392.html
Copyright © 2011-2022 走看看