python语法详解

来源:互联网 发布:农产品淘宝店铺取名 编辑:程序博客网 时间:2024/06/06 23:14

【文件首部/编码声明】

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # 声明脚本使用 utf-8 编码是为了在脚本中含有中文时也能被正确解释运行

【注释】
    # here we can put a comment, 在井号后添加注释。

【缩进/大小写】
    必须使用 4 个空格进行缩进。python是大小写敏感的语言

【普通数据类型】
    整数    1,100,-123,0
    浮点数    3.14,-9.01,1.2e9,1.2e-5
    普通字符串    'Hello\tWorld.\n'
    普通字符串    "I'm Chica, how're u?"
                        'ABCDEFG'[:3] = 'ABC'
                        'ABCDEFG'[::3] = 'ADG'
    多行字符串    '''line1
                           line2
                           line3'''
    不经转义的原始字符串    r'Hello\tWorld.\n'
    不经转义的原始多行字符串    r'''MultilineString'''
    Unicode编码的字符串    u'HelloFrog'
    二进制字符串    b'HelloBinary'
    布尔值    true,false
    空值    none

【高级数据类型】
    列表    zone = ['China', 'USA', 'England']

               zone[0] = 'China'

               zone[:1] = ['China']

               zone[:2] = ['China', 'USA']

               zone[-1] = 'England'

               zone[-2:] = ['USA', 'England']

               zone[0::2] = ['China', 'England']    # 以 2 为步长从第 0 个元素到最后一个元素进行取值

               len(zone) = 3
               # 列表的值是可修改的
    元组    name = ('Zhao', 'Qian', 'Sun')
               name[1:] = ('Qian', 'Sun')
    只含一个数值元素的元组    num = (1, )
              # 元组的值是不可修改的,所以数据更安全
              # 但是可以在元组中定义列表,元组中包含的列表的所属元素是可修改的
    字典    d = {'Zhao':175, 'Qian':162, 'Sun':170}
               d['Zhao'] = 175
               if 'Zhao' in d :
                   # 如果 'Zhao' 被包含在字典中则执行至此
    集合    s = set([1, 2, 2, 3, 3, 3])
               s = set([1, 2, 3])    # set 会去掉集合中重复的元素
               s1 & s2    # 计算交集
               s1 | s2    # 计算并集


【杂项】

    删除自定义变量myVar    globals().pop('myVar')

    Windows清屏    os.system('cls')    #需要先执行命令import os导入os模块

    Linux清屏    os.system('clear')


【运算符】
    赋值    =
    比较    >,<,==,>=,<=
    数值    +,-,*,/,%,**
    逻辑    and,or,not

【输入/输出】
[python] view plain copy
 print?
  1. name = raw_input('Name is? ')  
  2. age = int(raw_input('Age is? '))  
  3. print 'the content is %s, %d years old.' %(name, age)  

【格式化字符串】
    print "Hello %s, you're %d years old." %('Jack', 24)
    整数    %d
    字符串    %s
    浮点数    %f
    保留2位小数    %.2f
    十六进制    %x
    百分号    %%

【列表生成式】
[python] view plain copy
 print?
  1. # 列表生成表达式使用中括号[]  
  2. range(6)    # 生成 [0, 1, 2, 3, 4, 5]  
  3. range(192)    # 生成 [1, 3, 5, 7]  
  4. [x * x for x in range(14)]    # 生成 [1, 4, 9]  
  5. [x * x for x in range(14if x % 2 == 1]    # 生成 [1, 9]  
  6. [x + y for x in '12' for y in 'ab']    # 生成 [1a, 1b, 2a, 2b]  
  7. [x + '=' + y for x, y in {'x':'A''y':'B''z':'C'}.iteritems()]    # 生成 ['y=B', 'x=A', 'z=C']  
  8. [s.upper() for s in ['hell''heaven''god']]    # 生成 ['HELL', 'HEAVEN', 'GOD']  

【生成器】
1)方法一
[python] view plain copy
 print?
  1. # 生成器表达式使用小括号()  
  2. for y in (x * x for x in range(4)) :  
  3.     print y  
2)方法二
    # 把函数转换为生成器,在函数中包含 yield 关键字
    # yield 关键字会使脚本程序产生一个中断

【常用库函数/方法】
    int('123')    将字符串 '123' 转换为整数 123
    float('0.5')    将字符串 '0.5' 转换为浮点数 0.5
    str(123)    将数值 123 转换为字符串 '123'
    unicode(123)    将 123 转换为 unicode 编码格式的值 u'123'
    bool(a)    将 a 转换为布尔值。返回值为 true 或 false
    ord('A')    将字符转换成对应的 ASCII 码值
    chr(65)    将 ASCII 码值转换成对应的字符
    abs(-123)   返回数值 -123 的绝对值
    cmp(a, b)    比较 a 和 b 的大小。a>b 返回 1,a<b 返回 -1,a==b 返回 0
    len('string')    返回字符串的长度 或 返回列表的元素个数。1个汉字的长度是1
    sorted([4, 2, 3, 5, 1])    返回升序排序后的列表 [1, 2, 3, 4, 5]
    isinstance(x, str)    判断 x 是否为字符串,返回 true 或 false
    isinstance(x, Iterable)    判断 x 是否可迭代,返回 true 或 false
    open('./test.txt', 'r')    以只读方式打开文件 ./test.txt
    FILE.read()    将文件内容全部读取到内存中
    FILE.read(size)    读取 size 字节的文件内容到内存中
    FILE.readline()    读取文件中的 1 行到内存
    FILE.readlines()    将文件内容全部读取到内存中,并返回一个列表
    FILE.write('China1912')    向文件中写入字符串 'China1912'
    FILE.close()    关闭文件,释放文件句柄
    STR.encode('utf-8')    字符串方法,将 Unicode 编码的字符串 STR 转换为 utf-8 编码
    STR.decode('utf-8')    字符串方法,将 utf-8 编码的字符串 STR 转换为 Unicode 编码
    STR.replace('a', 'A')    字符串方法,将字符串 STR 中的字符 a 替换为字符 A
    LIST.append('France')    列表方法,在列表 LIST 末尾追加元素 France
    LIST.insert(1, 'France')    列表方法,在列表 LIST[1] 位置插入元素 France
    LIST.pop()    列表方法,返回列表 LIST 的末尾值并将该值从列表中删除
    LIST.pop(1)    列表方法,返回 LIST[1] 的值并将其从列表中删除
    LIST.sort()    列表方法,返回对元素排序后的列表
    DICT.get('Zhao')    字典方法,返回 Zhao 这个键对应的值
    DICT.get('Zhao', -1)    字典方法,返回 Zhao 这个键对应的值,若值不存在则返回默认值-1
    DICT.pop('Zhao')    字典方法,返回 Zhao 这个键对应的值,并将 Zhao 的键值对从字典中删除

【流程控制】
1)条件语句一
[python] view plain copy
 print?
  1. if a > b :  
  2.     ....  
  3. elif a == b :  
  4.     ....  
  5. else:  
  6.     ....  
2)条件语句二
[python] view plain copy
 print?
  1. if a :  
  2.     ....  
3)循环语句一
[python] view plain copy
 print?
  1. names = ['Zhao''Qian''Sun']  
  2. for man in names :  
  3.     print man  
4)循环语句二
[python] view plain copy
 print?
  1. num = 0  
  2. for x in [12345] :  
  3.     num = num + x  
5)循环语句三
[python] view plain copy
 print?
  1. for x in range(6) :  
  2.     num = num + x  
6)循环语句四
[python] view plain copy
 print?
  1. for count, val in enumerate(['a''b''c']) :  
  2.     print count, val  
7)循环语句五
[python] view plain copy
 print?
  1. for x, y in [(1,2), (3,4), (5,6)] :  
  2.     print x, y  
8)循环语句六
[python] view plain copy
 print?
  1. for key in {'a':1'b':2'c':3} :  
  2.     print key  
9)循环语句七
[python] view plain copy
 print?
  1. num = 0  
  2. for x in [12345] :  
  3.     num = num + x  

【函数定义】
1)普通函数
[python] view plain copy
 print?
  1. def my_function(x=0) :    # 0是参数 x 的默认值  
  2.     print "this is my_function(%d)" %(x)  
  3.     y = 2 * x  
  4.     return x, y    # 返回多个值,实际上返回的是元组(x, y)  
2)空函数
[python] view plain copy
 print?
  1. def nop():  
  2.     pass  
3)可变参数函数一:
[python] view plain copy
 print?
  1. def my_function(numSet=[7,8,9]):    # 参数传值,调用形式为 my_function([1,2,3])  
  2.     for x in numSet:  
  3.         print x  
  4.     return len(numSet)  
4)可变参数函数二:
[python] view plain copy
 print?
  1. def my_function(*numSet):    # 参数传址,调用形式为 my_function(1,2,3)  
  2.     for x in numSet:  
  3.         print x  
5)匿名函数
[python] view plain copy
 print?
  1. map(lambda x: x + 1, [123])  
  2. f = lambda x: x * 2  
  3. f(3) = 6  

【函数名也是变量】
    # 函数名也是变量,可以作为参数传递、赋值、返回
1)赋值到其它变量
[python] view plain copy
 print?
  1. f = abs  
  2. f(-2) = 2  
2)重定义函数名
[python] view plain copy
 print?
  1. abs = 5  
  2. abs(-2)    # 会报错。要恢复 abs 为绝对值函数需要重启 python  
3)作为入口参数
[python] view plain copy
 print?
  1. def my_function(a, b, fn) :  
  2.     return fn(a + b) * fn(a)  
4)作为入口参数的经典示例
[python] view plain copy
 print?
  1. # 下列这些以函数作为参数的函数又称为高阶函数  
  2. map(fn, [x1, x2, x3, ...]) = [fn(x1), fn(x2), fn(x3), ...]  
  3. map(abs, [-1, -2, -3]) = [123]  
  4. map(str, [123456]) = ['12''34''56']  
  5. map(lambda x: x + 1, [123]) = [234]  
  6. reduce(fn, [x1, x2, x3, x4, x5, ...]) = fn(...fn(fn(fn(fn(x1, x2), x3), x4), x5), ...)  
  7. reduce(add, [1234]) = add(add(add(12), 3), 4) = 10  
  8. reduce(lambda x, y: x + y, [123]) = ((1 + 2) + 3) = 6  
  9. filter(my_isOdd, [123456789]) = [13579]  
  10. sorted([42351]) = [12345]  
  11. sorted([42351], my_reversed) = [54321]  
5)作为返回值
    #函数作为返回值时可实现闭包、装饰器

【闭包】
    # 闭包的概念比较高级,之后单独开篇文章进行讲解

【模块】
    # 脚本 test.py 也可称作模块,将其放置于单独的文件夹 AAA 中
    # 同时在文件夹 AAA 里新建一个 __init__.py 脚本,该脚本可以为空
    # 此时文件夹就是一个包(Package)
    # 模块调用形式为 AAA.test
1)验证模块是否以被导入模式启动
[python] view plain copy
 print?
  1. if __name__ == '__main__' :    # 直接运行模块时,__name__ 的值是 '__main__'  
  2.     print 'Running independently.'  
  3. else:  
  4.     print 'Running by import.'  
2)第三方库
    # 安装命令为 pip install XXX
    PIL    图像处理支持库
    MySQL-python    MySQL支持库
    numpy    科学计算支持库
    Jinja2    文本模板支持库

【异常处理】
1)普通异常处理
[python] view plain copy
 print?
  1. # 捕获异常后会运行异常处理,并停止执行后续代码  
  2. ......  
  3. try:    # 尝试运行可能出错的代码  
  4.     print 'trying...'  
  5.     result = 20 / int( input )  
  6.     print 'result:', result  
  7. except ValueError, e:    # 如果出现数值错误  
  8.     print 'ValueError:', e  
  9. except ZeroDivisionError, e:    # 如果出现除数错误  
  10.     print 'ZeroDivisionError:', e  
  11. else:    # 如果没有出现错误  
  12.     print 'No error occured!'  
  13. finally:    # 无论是否出错都会运行的代码  
  14.     print 'This is finally statement.'  
  15. print 'Done!'    # 如果捕获到错误,这句打印不会被执行  
2)错误日志记录
[python] view plain copy
 print?
  1. # 捕获异常后会将异常记录到 log 日志,并继续执行后续代码  
  2. import logging  
  3. ......  
  4. try:  
  5.     print 'trying...'  
  6.     result = 20 / int( input )  
  7.     print 'result:', result  
  8. except ZeroDivisionError, e:    # 如果出现除数错误  
  9.     logging.exception(e)    # 记录错误信息到 log 日志文件,之后继续运行后续代码  
  10. print 'Done!'    # 即便发生了错误,这句打印仍可执行  
3)自定义抛出异常
[python] view plain copy
 print?
  1. # 先要自定义一个异常类,设定好继承关系  
  2. # 之后就可以抛出该自定义异常  
  3. # 优先使用 python 库中的异常类型,只在必要的时候自定义异常类型  
  4. class customError(StandardError):    # 自定义异常类  
  5.     pass  
  6. if input == none :    # 异常产生条件  
  7.     raise customError('customError occured: value is none.')    # 抛出自定义异常  
  8. else:  
  9.     print input  
4)向上抛出异常
[python] view plain copy
 print?
  1. # 如果当前异常捕获过程中没有合适的异常处理代码,可以将异常抛给上层处理  
  2. ......  
  3. try:  
  4.     result = 20 / int( Input )  
  5. except StandardError, e:  
  6.     print 'StandardError occured!'  
  7.     raise    # 将异常直接抛给上层  
  8.     # 另一种方式是像下方注释那样指定一个异常类型抛给上层  
  9.     # raise ValueError('invalid input value!')    # 向上层抛出一个 ValueError 异常  

【调试】
1)使用断言替代打印
[python] view plain copy
 print?
  1. assert result != 0'result is 0.'    # 如果 assert 后的表达式值为 false 则打印 'result is 0'  
    # 使用 -0 参数关闭脚本中的断言
    $python -0 test.py
2)使用 logging 记录异常日志
[python] view plain copy
 print?
  1. # 可以指定 INFO、DEBUG、WARNING、ERROR 四个类别,非常有用  
  2. import logging    # 导入 logging 模块  
  3. logging.basicConfig( level = logging.INFO )  
  4. ......  
  5. div = int( Input )  
  6. logging.info('div = %d' %(div))    # 如果出错则添加信息到异常日志  
  7. print 20 / div  
3)调试器单步调试
    # 使用 -m pdb 参数运行脚本
    $python -m pdb test.py
    # 在 pbd 中,输入命令 l 查看脚本代码,输入 n 执行下一条语句,输入 p <变量名> 查看变量值,输入 q 退出调试工具。
4)设置断点
[python] view plain copy
 print?
  1. # 代码运行到断点处后,可以输入 c 继续执行后续语句,输入 p <变量名> 可查看变量值  
  2. import pdb  
  3. div = int( Input )  
  4. pdb.set_trace()    # 设置断点,代码运行至此会暂停  
  5. print 20 / div  

【文件I/O操作】
1)普通写法
[python] view plain copy
 print?
  1. try:  
  2.     pf = open('./text.txt''r')  
  3.     content = pf.read().decode('utf-8')    # 读取文件内容并解码  
  4. except IPError, e:  
  5.     print 'open file error.'  
  6. finally:  
  7.     if pf:  
  8.         pf.close()    # 普通写法中必须显示关闭文件以释放文件句柄  
2)简化写法
[python] view plain copy
 print?
  1. # 使用 with 语句的简化写法不必写明关闭文件的操作,而由系统自动完成      
  2. with open('./test.txt''rw') as pf:  
  3.     pf.write('China1912')  
  4.     print f.read()  
3)读取文件时解码
[python] view plain copy
 print?
  1. import codecs  
  2. with codecs.open('./test.txt''rb''utf-8') as pf:    # 读取文件时将内容解码  
  3.     pf.read(1024)    # 读取 1024 字节解码后的数据  

【模拟 shell/cmd 操作】
1)os 模块
[python] view plain copy
 print?
  1. import os  
  2. os.name    # 操作系统的名字,'posix' 表示 Linux/Mac OS,'nt' 表示 Windows  
  3. os.uname()    # 系统详细信息,Windows 下不可用  
  4. os.environ    # 操作系统的环境变量  
  5. os.getenv('PATH')    # 打印环境变量 PATH 的值  
  6. os.system('echo hello')    # 在当前系统的 shell 中执行 'echo hello' 命令  
  7. os.path.abspath('.')    # 获取当前目录的绝对路径  
  8. os.path.isfile(path)    # 检测 path 是否是文件  
  9. os.path.isdir(path)    # 检测 path 是否是目录  
  10. os.path.exists(path)    # 检测 path 路径是否存在  
  11. os.path.join('/usr/bin/''mydir')    # 生成一个新的路径 '/usr/bin/mydir'  
  12. os.path.chdir(path)    # 更改工作目录为 path  
  13. os.path.listdir(path)    # 列出 path 目录下的所有文件和目录  
  14. os.path.getsize(path)    # 获取 path 路径指向文件的大小,若 path 指向目录返回 0  
  15. os.mkdir('/usr/bin/mydir')    # 创建目录 /usr/bin/mydir  
  16. os.rmdir('/usr/bin/mydir')    # 移除目录 /usr/bin/mydir  
  17. os.path.split('/usr/bin/test.txt')    # 将路径 '/usr/bin/test.txt' 拆分成元组 ('/usr/bin', 'test.txt'),获得文件名  
  18. os.path.splitext('/usr/bin/test.txt')    # 将路径 '/usr/bin/test.txt' 拆分成元组 ('/usr/bin/test/', '.txt'),获得文件后缀  
  19. os.rename('test.txt''prime.txt')    # 将文件 test.txt 重命名为 prime.txt  
  20. os.remove('test.txt')    # 删除文件 test.txt  
2)shutil 模块
[python] view plain copy
 print?
  1. import shutil  
  2. shutil.copyfile('./test.txt''./mydir/newTest.txt')    # 复制文件 ./test.txt 到 ./mydir/newTest.txt  
  3. shutil.copytree(srcDir, destDir, False)    # 将 srcDir 目录树拷贝到 destDir 下,并将所有符号链接指向的文件进行实体拷贝,而不是只拷贝符号链接  
  4. 转自:http://blog.csdn.net/qidi_huang/article/details/51584476



   在许多Python程序中,都会存在一行if __name__ == '__main__':代码,这里我就详细说明一下它的作用。


1、这段代码的功能
   一个python的文件有两种使用的方法,第一是直接作为脚本执行,第二是import到其他的python脚本中被调用(模块重用)执行。因此if __name__ == '__main__': 的作用就是控制这两种情况执行代码的过程,在if __name__ == '__main'__: 下的代码只有在第一种情况下(即文件作为脚本直接执行)才会被执行,而import到其他脚本中是不会被执行的。
2、运行的原理
   每个python模块都包含一个内置的变量,即__name__,当运行模块(.py文件)被执行的时候,__name__等于文件(包含了后缀.py);如果import到其他模块中,则__name__等于模块名称(不包含后缀.py)。而“__main__”等于当前执行文件的名称(包含了后缀.py)。进而当模块被直接执行时,__name__ == '__main__'结果为真。


例子:

创建一个name.py的文件:

[python] view plain copy
  1. if __name__ == '__main__':  
  2.     yourname = 'xiaoli'  
  3.     print('your name is',yourname)  
运行程序直接输出:your name is xiaoli


再创建另一个文件main.py:

[python] view plain copy
  1. import name  
  2. name.__name__  
运行程序没有任何显示,即是不能执行name.py的内容

这是时候只要将name.py代码改为:

[python] view plain copy
  1. #if __name__ == '__main__':  
  2. yourname = 'xiaoli'  
  3. print('your name is',yourname)  
再次运行main.py,即可以显示your name is xiaoli

因此,一句话来说if __name__ == '__main__':就是用来检验py文件是不是作用脚本直接调用



                                                                                                                                            

1.java里get/set方法

大部分的同学开始写java代码的时候,最初始的代码肯定是字段的get/set方法。大家对于java特别冗长的诟病,很大一部分来自于无处不在的get/set方法。甚至国内有相当一部分不负责任的java书籍,里面靠大段的get/set代码来拼凑篇幅。。。 
来个最简单的例子,估计大家都写过类似的代码:

public class Person {    private int age;    public Person(int age) {        this.age = age;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

2.python里的get/set方法

python里如果按java的那一套写法,代码应该像是这样:

class Person(object):    def __init__(self):        self._age = None    def get_age(self):        return self._age    def set_age(self,age):        if(isinstance(age,str)):            self._age = int(age)        elif(isinstance(age,int)):            self._age = age
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

显然这是java风格的代码,python的哲学是简洁明了,这么麻烦的代码显然不是我们想要的。如果我们想直接访问上面Person类的age属性,也得使用get/set方法,否则会报错:

p = Person()p.set_age("18")print p.get_age() #OK,没问题print p.age #会报错,'Person' object has no attribute 'age'
  • 1
  • 2
  • 3
  • 4

3.property方法

如果我们想在py中直接访问属性,比如想在上面的例子中直接访问Person的age字段,可以在Person类的最后加如下一行代码:

age = property(get_age,set_age)
  • 1

这样,我们就直接可以访问age字段了:

p = Person()p.age = 18print p.get_age() #OK,没问题,返回的结果是18print p.age #OK,没问题,返回的结构也是18
  • 1
  • 2
  • 3
  • 4

上面是用函数模式的方式来使用property的。当然我们也可以用装饰器的模式使用。

class Person(object):    def __init__(self):        self._age = None    @property    def age(self):        return self._age    @age.setter    def age(self,age):        if isinstance(age,str):            self._age = int(age)        elif isinstance(age,int):            self._age = age    @age.deleter    def age(self):        del self._agep = Person()p.age = "18"print p.age #18del p.ageprint p.age #报错,AttributeError: 'Person' object has no attribute '_age'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

上面使用property装饰器模式的时候注意几个小点: 
1.三个函数的名字与字段名是一样的。 
2.使用proterty可以比较简单实现字段的读写控制。例如想要字段为只读属性,那么只需要提供getter方法,上面的setter方法可以去掉。

4.用property定义需要计算的属性

同时我们还可以用property来定义需要进行计算的字段。这些字段不会保存在对象中,只有当我们实际需要的时候才会完成真正计算。

class Person(object):    def __init__(self):        self._age = None    @property    def age(self):        return self._age    @age.setter    def age(self,age):        if isinstance(age,str):            self._age = int(age)        elif isinstance(age,int):            self._age = age    @property    def height(self):        return self.age * 10p = Person()p.age = ("18")print p.height #180
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

上面的例子,就是根据年龄来推算身高。。

5.property的基本原理

在python中,property()是一个内置的函数。他的原型如下:

   def __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 attribute        fget is a function to be used for getting an attribute value, and likewise        fset is a function for setting, and fdel a function for del'ing, an        attribute.  Typical use is to define a managed attribute x:        class C(object):            def getx(self): return self._x            def setx(self, value): self._x = value            def delx(self): del self._x            x = property(getx, setx, delx, "I'm the 'x' property.")        Decorators make defining new properties or modifying existing ones easy:        class C(object):            @property            def x(self):                "I am the 'x' property."                return self._x            @x.setter            def x(self, value):                self._x = value            @x.deleter            def x(self):                del self._x        # (copied from class doc)        """        pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

在python的源码中,我们就很容易看出property的用法。其中,fget是一个获取字段值的函数,而fget是一个设置字段值的函数,fdel是一个删除属性的函数,doc是一个字符串(类似于注释)。从函数实现上看,这些函数参数都是可选的,默认为None,调用的其实就是get,set,del方法!


原创粉丝点击