zoukankan      html  css  js  c++  java
  • [读书]Python学习手冊--属性管理1

    属性管理-特性

    一般开发这不必关心属性的实现。对工具的构建这来说,了解这一块对API的灵活性有帮助。
    大多数情况下,属性位于对象自身之中。或者继承自对象所派生自的一个类。 ----python学习手冊

    property

    property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
    fget 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, an attribute.
    能够使用函数的方式也能够使用装饰器的方式来使用

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    #python2.7x
    #property.py  @2014-07-26
    #author: orangleliu
    
    class Person(object):
        def __init__(self, name):
            self._name = name 
        
        def getName(self):
            print 'fetch....'
            return self._name
        
        def setName(self, value):
            print 'change...'
            self._name = value
        
        def delName(self):
            print 'remove....'
            del self._name
            
        #也能够使用装饰器的方式
        name = property(getName, setName, delName, "name property docs")
        
    bob = Person('Bob')
    print bob.name
    print Person.name.__doc__
    bob.name = 'bob'
    print bob.name
    del bob.name
    #print bob.name
    
    '''
    并没有想象中的那么好使
    
    #类没有继承object的情况下
    fetch....
    Bob
    name property docs
    bob
    set del 就没有使用啊
    
    #类继承object的情况下
    Bob
    name property docs
    change...
    fetch....
    bob
    remove....
    '''


    书中的样例并没有继承object, 使用2.7的版本号和书中结果不一致。 须要继承object才干达到预期的结果

    加入属性的默认操作

    这里使用装饰的方式, 仅仅要value赋值就进行一个默认的操作。能够看到我们使用属性的方式就能够默认调用函数来处理属性。

    g.value 而不是 g.valueXX()

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    #python2.7x
    #property.py  @2014-07-26
    #author: orangleliu
    
    class GetSquare(object):
        def __init__(self, num):
            self.value = num
            
        @property
        def value(self):
            return self._value
        
        @value.setter
        def value(self, num):
            self._value = num**2
            
    '''
    从上面能够看到set属性值的时候作了一些属性的某人动作,有时候非常有必要
    '''
    
    g = GetSquare(4)
    print g.value
    
    g.value = 10 
    print g.value


    事实上这样的方式非常类似于javabean中的方式。

  • 相关阅读:
    Sublime text 2 全平台破解总结
    wordpress get_header 函数学习
    <转> Sublime Text 2 使用心得
    sublime 打开命令窗口监控
    linux环境搭建
    [摘]不容错过的window8 metro UI风格的web资源
    Sublime Text 2报“Decode error output not utf8”错误的解决办法
    <转>My sublime text (Windows) cheat sheet
    JavaScript 语言基础知识点总结(思维导图)
    bootstrap学习资源
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/6972915.html
Copyright © 2011-2022 走看看