zoukankan      html  css  js  c++  java
  • property 用法

     1 _DEFAULT_CONFIG = {
     2     'name':None
     3 }
     4 
     5 class TestProperty(object):
     6     def __init__(self, config):
     7         self._config = config or {}
     8 
     9     def __GetName(self):
    10         return self._config['name']
    11 
    12     def __SetName(self, name):
    13         self._config['name'] = name
    14     
    15     def __DeleteName(self):
    16         del self._config['name']
    17 
    18     name = property(__GetName, __SetName, __DeleteName)
    19 
    20 if __name__ == '__main__':
    21     tp = TestProperty(_DEFAULT_CONFIG)
    22     tp.name = '250'
    23     print tp.name
    24     del tp.name
    25     print tp.name #抛错,已经没有name属性

    property 函数原型property([fget[, fset[, fdel[, doc]]]])

    fget,fset,fdel 分别为取值,设值,删除值

    函数自动为对象生成name属性,前提是类定义时不能有属性name,否则property函数会自动覆盖将原name属性覆盖。

    @property

    创建只读属性可以用@property

     1 class Property(object):
     2     def __init__(self):
     3         self.name = 'leon liang'
     4 
     5     @property
     6     def username(self):
     7         return self.name
     8 
     9     @property
    10     def password(self, bb): #这是错误的,调用时会出错
    11         return bb + 1
    12 
    13 if __name__ == '__main__':
    14     obj = Property()
    15     print obj.username
    16     print obj.password(1) #调用出错
  • 相关阅读:
    使用OpenCV进行相机标定
    近景摄影测量
    vmware安装操作系统
    mac下使用gnu gcc
    Collection of Boot Sector Formats for ISO 9660 Images
    java会不会出现内存泄露
    difference between http get and post
    Apache许可翻译
    项目持续集成工具
    常用的地图投影算法
  • 原文地址:https://www.cnblogs.com/bjdxy/p/2769415.html
Copyright © 2011-2022 走看看