初、浅学python

初、浅学python

基本语法

  • python解释器提示符,>>>

  • 退出,在GNU/Linux 或者 OS X shell ctrl + dexit(),在Windows 命令提示符ctrl + z

  • 打开python文件 python xxx.py

  • python区分大小写

  • 内置help功能,help('len')会显示len函数的帮助,按q退出。

  • 注释,#

  • int类型可以是任意大小的整数,没有单独的long

  • 单引号和双引号字符串完全相同,三引号"""'''指定多行字符串,可以在三引号中自由地使用单引号和双引号,双引号可以直接显示单引号不需要转移符,三引号可以直接显示双引号和单引号

    '''This is a multi-line string. This is the first line.
    This is the second line.
    "What's your name?," I asked.
    He said "Bond, James Bond."
    '''
    
  • 没有单独的char类型

  • format,将每个参数值替换到指定的位置

    age = 20
    name = 'Swaroop'
    
    print('{0} was {1} years old when he wrote this book'.format(name, age))
    print('Why is {0} playing with that python?'.format(name))
    
    print(name + ' is ' + str(age) + ' years old')
    
    # 取十进制小数点后的精度为 3 ,得到的浮点数为 '0.333'
    print('{0:.3f}'.format(1.0/3))
    # 填充下划线 (_) ,文本居中
    # 将 '___hello___' 的宽度扩充为 11 
    print('{0:_^11}'.format('hello'))
    # 用基于关键字的方法打印显示 'Swaroop wrote A Byte of Python'
    print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))
    
  • print,总是以一个不可见的 「新的一行」 字符(\n)作为结尾,为了防止这个换行符被打印输出,你可以指定它以一个空end=''

    #ab
    print('a', end='')
    print('b', end='')
    
    #a b c
    print('a', end=' ')
    print('b', end=' ')
    print('c')
    
  • 在字符串中,行末尾的单个反斜杠表示字符串在下一行中继续,但不添加换行符。

    "This is the first sentence.\
    This is the second sentence."
    #等价于
    "This is the first sentence. This is the second sentence."
    
  • 字符串包含特殊字符,可以使用r或R,指定原始字符串r"Newlines are indicated by \n",常用于正则表达式

  • 标识符,必须字母或下划线_开头,其余可由字母下划线数字组成,区分大小写

  • 变量,变量可以直接通过赋值来使用,不需要任何声明或者数据类型定义。

  • 缩进,Python 将始终使用缩进进行分块,永远不会使用花括号。

运算符与表达式

  • 'AA'*2,字符串可以用*,等于重复若干次

  • //,除且取整,向下取整

  • &按位与,|按位或,^按位异或,~按位取反,not布尔非,and布尔与,or布尔或

  • 优先级

    (expressions...), [expressions...], {key: value...}, {expressions...} : 绑定或者元组显示,列表显示,字典显示,设置显示
    x[index], x[index:index], x(arguments...), x.attribute :订阅,切片,调用,属性引用
    ** :求幂
    +x, -x, ~x :正负号,按位非
    *, /, //, % :乘除法,取整和取余
    +, - :加减法
    <<, >> :移位
    & :按位与
    ^ :按位异或
    | :按位或
    in, not in, is, is not, <, <=, >, >=, !=, == :比较,包括成员资格测试和身份测试
    not x :布尔非
    and :布尔与
    or :布尔或
    if - else :条件表达式
    lambda :Lambda 表达式

  • length = 5
    breadth = 2
    
    area = length * breadth
    print('Area is', area) # Area is 10 ,注意python自动加了空格
    print('Perimeter is', 2 * (length + breadth)) # Perimeter is 14
    

控制流

  • if

    number = 23
    guess = int(input('Enter an integer : '))
    
    if guess == number:
        # 新程序块的开始处
        print('Congratulations, you guessed it.')
        print('(but you do not win any prizes!)')
        # 新程序块的结尾处
    elif guess < number:
        # 另一个程序块
        print('No, it is a little higher than that')
        # 你可以在程序块中“为所欲为”——做任何你想做的事情
    else:
        print('No, it is a little lower than that')
        # 只有当猜测数大于给定数的时候,才会执行此处
    
    print('Done')
    # 在 if 语句执行结束后,最后的这句语句总是会被执行。
    
  • while,在 while 循环中可以有一个 else 从句。

    number = 23
    running = True
    
    while running:
        guess = int(input('Enter an integer : '))
    
        if guess == number:
            print('Congratulations, you guessed it.')
            # 这会导致 while 循环停止
            running = False
        elif guess < number:
            print('No, it is a little higher than that.')
        else:
            print('No, it is a little lower than that.')
    else:
        print('The while loop is over.')
        # 你可以在此处继续进行其它你想做的操作
    
    print('Done')
    
  • forfor in

    for i in range(1, 5):  #内置函数 range 来生成这个数字序列,左闭右开
        print(i) #1 2 3 4
    else:
        print('The for loop is over') 
    

    rang(),默认步长为1,第三个数为步长,

    for i in range(1,6,2):
        print(i) # 1 3 5
    else:
        print('The for loop is over') 
    
  • break,中断循环语句,注意:中断一个forwhile循环,任何相应循环的 else 语句块都不会被执行。

    while True:
        s = input('Enter something : ')
        if s == 'quit':
            break
        print('Length of the string is', len(s)) # len()获取字符串长度
    print('Done')
    
  • continue,跳过当前循环语句块中的其余部分,然后继续执行循环的下一个迭代

    while True:
        s = input('Enter something : ')
        if s == 'quit':
            break
        if len(s) < 3:
            print('Too small')
            continue
        print('Input is of sufficient length')
        # 其它操作...
    

函数

  • 使用def定义函数,def 函数名():

    def say_hello():
        # 属于该函数的语句块
        print('hello world')
    # 函数结束
    
    say_hello()  # 调用函数
    say_hello()  # 再次调用函数
    
  • 函数参数, 函数定义时括号中的参数叫做 形参,而调用函数时提供的参数叫 实参

    def print_max(a, b):
        if a > b:
            print(a, 'is maximum')
        elif a == b:
            print(a, 'is equal to', b)
        else:
            print(b, 'is maximum')
    
    # 直接传递字面量
    print_max(3, 4)
    
    x = 5
    y = 7
    
    # 传递变量作为实参
    print_max(x, y)
    
  • 局部变量,函数中声明的变量

    x = 50
    
    def func():
        global x
    
        print('x is', x) #50
        x = 2
        print('Changed global x to', x) #2
    
    func()
    print('Value of x is', x) #50
    
  • global语句,不在任何函数或类的定义内的变量也叫做程序的顶级 top level 变量,在函数内给这种变量赋值,需要告诉 Python 这个变量并非本地变量,它是一个 全局变量。使用 global 语句你就不可能给在函数外定义的变量赋值。
    global x, y, z

    x = 50
    
    def func():
        global x
    
        print('x is', x) #50
        x = 2
        print('Changed global x to', x) #2
    
    func()
    print('Value of x is', x) #2
    
  • 默认参数值,函数定义时给某些形参名后加上赋值操作符 = 与对应形参的默认值,注意,形参的默认值必须是常数,默认值是不可改变的

    def say(message, times=1):
        print(message * times)
    
    say('Hello')	#Hello
    say('World', 5)		#WorldWorldWorldWorldWorld
    

    注意:只有形参末尾才能指定默认值

    def say(message, times=1, age=2):
        print(message * times * age)
    
    say('Hello') 	# 两次
    say('World', 5) 	# 10次
    
  • 关键字参数,如果你的一些函数需要许多参数,而你只想指定其中的一部分。那么你可以通过为这些参数命名来给它们赋值,这叫做 关键字参数。

    def func(a, b=5, c=10):
        print('a is', a, 'and b is', b, 'and c is', c)
    
    func(3, 7)
    func(25, c=24)
    func(c=50, a=100)
    
  • 可变形参,定义一个能接收任意个数参数的函数定义一个能接收 任意个 数参数的函数,*实现

    def total(a=5, *numbers, **phonebook):
        print('a', a)	#10
    
        # 遍历元组中的所有项
        for single_item in numbers:
            print('single_item', single_item)	# single_item 1 single_item 2 single_item 3 
    
        # 遍历字典中的所有项
        for first_part, second_part in phonebook.items():
            print(first_part,second_part)	# Inge 1560 John 2231 Jack 1123
    
    print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))
    

    当我们声明一个带星号的参数 *param 时,从这个参数开始,之后的所有参数都会被收集进入一个名为 param 的元组中。类似的,当我们定义了一个带两个星号的参数 **param 时,从这个参数开始,之后的所有参数都会被收入名为 param 的字典中。

  • return语句,从函数跳出时返回一个值,如果你的函数没有 return 语句,系统会自己在函数的结尾添加 return None 语句

    def some_function():
        pass
    

    pass 语句在 Python 中用于表示一个空的语句块,通常用于占位。

  • 文档字符串DocStrings

    def print_max(x, y):
        '''Prints the maximum of two numbers.
    
        The two values must be integers.'''
        # 如果有必要,将参数转为整数
        x = int(x)
        y = int(y)
    
        if x > y:
            print(x, 'is maximum')
        else:
            print(y, 'is maximum')
    
    print_max(3, 5)
    print(print_max.__doc__)
    

    一个函数逻辑上第一行的字符串是这个函数的 DocStrings,模块 和 类 都有各自的 DocStrings。
    书写惯例是:首行首字母大写,结尾有句号;第二行为空行;第三行以后为详细的描述。
    print_max 函数的 __doc__ 属性来访问它的 DocStrings,注意:属性 doc 的前后都有两个下划线。

模块

  • 利用 import 引入模块

    import sys
    
    print('The command line arguments are:')
    for i in sys.argv:
        print(i)
    
    print('\n\nThe PYTHONPATH is', sys.path, '\n')
    ##############################################################################
    python module_using_sys.py we are arguments    # 每个参数都由空格隔开
    The command line arguments are:
    module_using_sys.py
    we
    are
    arguments
    
    The PYTHONPATH is ['/tmp/py',
    # 这有很多条目,在这里没有全部显示
    '/Library/Python/2.7/site-packages',
    '/usr/local/lib/python2.7/site-packages']
    

    sys.argv 包含 命令行参数 列表,即那些使用命令行传递给程序的参数。

    当前运行的模块名总储存在 sys.argv 列表的第一个元素中。所以执行以上语句后,sys.argv[0] 中存放着 module_using_sys.pywe放在 sys.argv[1], are 放在 sys.argv[2]arguments 放在 sys.argv[3]

    sys.path 是模块导入时要搜索的目录列表。

    当前目录指的是你的程序启动的目录。你可以通过执行 import os; print(os.getcwd()),来查看你的程序的当前目录。

  • 字节码文件.pyc,导入模块是一个相对而言开销较大的操作,因此,Python 试用了一些手段来使得导入模块的操作更加快速。其中一个方法,就是创建以 .pyc 为扩展名的 字节码 文件,当你下一次想要在另外一个程序代码中导入模块的时候,这个 .pyc 文件就很有用 —— 导入操作会很快完成,这是因为导入模块所必须的一部分操作已经被事先完成了。
    注意:这些 .pyc 文件一般会被创建在与它对应的 .py 文件相同的文件目录下。如果 Python 没有在该文件夹下写文件的权限,那么 .pyc 文件将不会被创建。

  • from…import语句,直接把 argv 变量导入到你的程序中(以避免每次都要键入 sys.),可以使用 from sys import argv 语句。
    警告:原则上来说,要 避免 使用 from..import 语句,而是使用 import 语句。这是因为如果使用 import 语句的话,你的程序会避免出现命名冲突的问题,并且代码的可读性更高。

    from math import sqrt
    print("Square root of 16 is", sqrt(16))
    
  • 模块的_name_,每一个模块都有一个名称,在模块中我们可以通过判断语句来确定模块的名称,确定模块被导入了?还是在独立地运行。

    if __name__ == '__main__':
        print('This program is being run by itself')	# 模块独立运行,打印
    else:
        print('I am being imported from another module')	# 模块导入,打印
    
  • 创建自己的模块

    这个模块的位置有两种选择:1、导入它的程序所处的文件夹下;2、sys.path 所列出的文件夹下。

    def say_hi():
        print('Hi, this is mymodule speaking.')
    
    __version__ = '0.1'
    ##########################################
    import mymodule
    
    mymodule.say_hi()	# Hi, this is mymodule speaking.
    print('Version', mymodule.__version__)	# Version 0.1
    
  • Python 的指导原则之一,就是「显式优于隐式」。

  • dir函数,以列表的形式返回某个对象定义的一系列标识符,如果这个对象是个模块,返回的列表中会包含模块内部所有的函数、类和变量。
    这个函数接收一个可选的参数。当参数是模块名时,函数会返回对应模块的标识符列表。没有参数时则会返回当前模块的标识符列表。

  • 程序包,程序包就是一个装满模块的文件夹,它有一个特殊的 __init__.py 文件,这个文件告诉 Python 这个文件夹是特别的,因为它装着 Python 的模块。
    假设你想创建一个叫做 world 的程序包,它有很多子程序包 asiaafrica 等。这些子程序包依次包含 indiamadagascar 等模块。

    - <some folder present in the sys.path>/
        - world/
            - __init__.py
            - asia/
                - __init__.py
                - india/
                    - __init__.py
                    - foo.py
            - africa/
                - __init__.py
                - madagascar/
                    - __init__.py
                    - bar.py
    

数据结构

  • Python 中有四种内置的数据结构 list, tuple, dictionary , set

  • List列表,有序项集合,在列表中存储一系列项,可变,[]

    # 这是我的购物清单
    shoplist = ['apple', 'mango', 'carrot', 'banana']
    
    print('I have', len(shoplist), 'items to purchase.')
    
    print('These items are:', end=' ')
    for item in shoplist:
        print(item, end=' ')
    
    print('\nI also have to buy rice.')
    shoplist.append('rice')
    print('My shopping list is now', shoplist)
    
    print('I will sort my list now')
    shoplist.sort()
    print('Sorted shopping list is', shoplist)
    
    print('The first item I will buy is', shoplist[0])
    olditem = shoplist[0]
    del shoplist[0]
    print('I bought the', olditem)
    print('My shopping list is now', shoplist)
    
    ##########################################输出
    python ds_using_list.py
    I have 4 items to purchase.
    These items are: apple mango carrot banana
    I also have to buy rice.
    My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
    I will sort my list now
    Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
    The first item I will buy is apple
    I bought the apple
    My shopping list is now ['banana', 'carrot', 'mango', 'rice']
    
  • tuple元组,将多个对象组合在一起,和字符串一样是不可变的 ,即你不能修改元组,()可不加可加,有序
    一个空的元组是由一对空的圆括号构成的,例如, myempty = ()
    一个项的元组,singleton = (2 , ) ,要有一个逗号

    # 尽管圆括号是可选的,
    # 我还是建议使用圆括号,
    # 来表示元组的开始和结束。
    # 因为显式总比隐式要好。
    zoo = ('python', 'elephant', 'penguin')
    print('Number of animals in the zoo is', len(zoo))
    
    new_zoo = 'monkey', 'camel', zoo    # parentheses not required but are a good idea
    print('Number of cages in the new zoo is', len(new_zoo))
    print('All animals in new zoo are', new_zoo)
    print('Animals brought from old zoo are', new_zoo[2])
    print('Last animal brought from old zoo is', new_zoo[2][2])
    print('Number of animals in the new zoo is',
          len(new_zoo)-1+len(new_zoo[2]))
    
    #########################################输出
    python ds_using_tuple.py
    Number of animals in the zoo is 3
    Number of cages in the new zoo is 3
    All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
    Animals brought from old zoo are ('python', 'elephant', 'penguin')
    Last animal brought from old zoo is penguin
    Number of animals in the new zoo is 5
    
  • dictionary字典,键值对,可变,d = {key1 : value1, key2 : value2 },键不能重复,无序,{}
    如果你在函数中使用了关键字参数,那么其实你已经使用了字典。

    # 'ab' 是 'a'ddress'b'ook 的缩写,意思是地址簿
    
    ab = {
        'Swaroop': 'swaroop@swaroopch.com',
        'Larry': 'larry@wall.org',
        'Matsumoto': 'matz@ruby-lang.org',
        'Spammer': 'spammer@hotmail.com'
    }
    
    print("Swaroop's address is", ab['Swaroop'])
    
    # 删除一个键值对
    del ab['Spammer']
    
    print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
    
    for name, address in ab.items():
        print('Contact {} at {}'.format(name, address))
    
    # 添加一个键值对
    ab['Guido'] = 'guido@python.org'
    
    if 'Guido' in ab:
        print("\nGuido's address is", ab['Guido'])
        
    #################################################输出
    python ds_using_dict.py
    Swaroop's address is swaroop@swaroopch.com
    
    There are 3 contacts in the address-book
    
    Contact Swaroop at swaroop@swaroopch.com
    Contact Matsumoto at matz@ruby-lang.org
    Contact Larry at larry@wall.org
    
    Guido's address is guido@python.org
    
  • 序列,列表,元组和字典都是序列的一种
    成员测试*(例如:innot in 表达式) 和 索引操作还有切片(提取子序列)
    切片时提供第三个参数 步长,默认的步长为 1

    shoplist = ['apple', 'mango', 'carrot', 'banana']
    name = 'swaroop'
    
    # 字符串索引 #
    print('Item 0 is', shoplist[0])
    print('Item 1 is', shoplist[1])
    print('Item 2 is', shoplist[2])
    print('Item 3 is', shoplist[3])
    print('Item -1 is', shoplist[-1])
    print('Item -2 is', shoplist[-2])
    print('Character 0 is', name[0])
    
    # 列表切片 #
    print('Item 1 to 3 is', shoplist[1:3])
    print('Item 2 to end is', shoplist[2:])
    print('Item 1 to -1 is', shoplist[1:-1])
    print('Item start to end is', shoplist[:])
    
    # 字符串切片 #
    print('characters 1 to 3 is', name[1:3])
    print('characters 2 to end is', name[2:])
    print('characters 1 to -1 is', name[1:-1])
    print('characters start to end is', name[:])
    
    #####################################################################输出
    python ds_seq.py
    Item 0 is apple
    Item 1 is mango
    Item 2 is carrot
    Item 3 is banana
    Item -1 is banana
    Item -2 is carrot
    Character 0 is s
    Item 1 to 3 is ['mango', 'carrot']
    Item 2 to end is ['carrot', 'banana']
    Item 1 to -1 is ['mango', 'carrot']
    Item start to end is ['apple', 'mango', 'carrot', 'banana']
    characters 1 to 3 is wa
    characters 2 to end is aroop
    characters 1 to -1 is waroo
    characters start to end is swaroop
    
    #################################################
    >>>shoplist = ['apple', 'mango', 'carrot', 'banana']
    >>>shoplist[::1]
    >>>['apple', 'mango', 'carrot', 'banana']
    >>>shoplist[::2]
    >>>['apple', 'carrot']
    >>>shoplist[::3]
    >>>['apple', 'banana']
    >>>shoplist[::-1]
    >>>['banana', 'carrot', 'mango', 'apple']
    
  • set集合,简单对象的无序的集合(collection),对象不可重复,可以确定它是否是另一个集合(set)的子集,找到两个集合之间的交集
    set 中的元素具有互异性,而 collection 中的元素不具有互异性。

    bri = set(['brazil', 'russia', 'india'])
    'india' in bri
    True
    'usa' in bri
    False
    bric = bri.copy()
    bric.add('china')
    bric.issuperset(bri)
    True
    bri.remove('russia')
    bri & bric # 或者是 bri.intersection(bric)
    {'brazil', 'india'}
    
  • 引用,你创建了一个对象,并把它赋值给一个变量时,这个变量只是引用了这个对象

    print('Simple Assignment')
    shoplist = ['apple', 'mango', 'carrot', 'banana']
    # mylist 只是指向同一个对象的另一个别名!
    mylist = shoplist
    
    # 我买下了第一件商品,所以把它从列表中移除
    del shoplist[0]
    
    print('shoplist is', shoplist)
    print('mylist is', mylist)
    # 注意到 shoplist 和 mylist 产生了同样的输出
    # 输出的都是没有 'apple' 的相同列表
    # 这验证了它们都指向着同一个对象
    
    print('Copy by making a full slice')
    # 通过全切片来获得一个副本
    mylist = shoplist[:]
    # 移除第一个元素
    del mylist[0]
    
    print('shoplist is', shoplist)
    print('mylist is', mylist)
    # 注意到现在这两个列表有差异了
    
  • 字符串方法

    # 这是一个字符串对象
    name = 'Swaroop'
    
    if name.startswith('Swa'):
        print('Yes, the string starts with "Swa"')	# 输出
    
    if 'a' in name:
        print('Yes, it contains the string "a"')	# 输出
    
    if name.find('war') != -1:
        print('Yes, it contains the string "war"')	# 输出
    
    delimiter = '_*_'
    mylist = ['Brazil', 'Russia', 'India', 'China']
    print(delimiter.join(mylist))	# Brazil_*_Russia_*_India_*_China
    

面向对象编程

  • 属于对象或者类的变量被称作,分为实例变量和类的变量。

  • self,等价于java的this

    有一个类 MyClass 以及这个类的一个对象叫做 myobject 。当你需要这样调用这个对象的方法的时候:myobject.method(arg1, arg2) ,这个语句会被 Python 自动的转换成 MyClass.method(myobject, arg1, arg2) 这样的形式

  • class Person:
        pass  # 一个空的语句块
    
    p = Person()
    print(p)	# __main__.Person instance at 0x10171f518>
    
  • 方法,

    class Person:
        def say_hi(self):
            print('Hello, how are you?')
    
    p = Person()
    p.say_hi()
    # 上面两行也可以写成下面这种形式
    # Person().say_hi()
    
  • __init__方法,在类的对象被初始化(也就是创建)的时候自动的调用,

    class Person:
        def __init__(self, name):
            self.name = name
    
        def say_hi(self):
            print('Hello, my name is', self.name)
    
    p = Person('Swaroop')
    p.say_hi()
    # 上面两行也可以写成下面这种形式
    # Person('Swaroop').say_hi()
    
  • 类和对象中的变量,类变量是共享的,对象变量属于每一个对象(实例)自身

    在 Python 中,所有的成员(包括数据成员)都是 公共的 ,所有的方法都是虚拟的。

    除非使用双下划线__privatevar会变成私有的

    class Robot:
        """代表一个机器人,拥有一个名字属性"""
    
        # 类属性,统计机器人的个数
        population = 0
    
        def __init__(self, name):
            """初始化数据"""
            self.name = name
            print("(Initializing {})".format(self.name))
    
            # 当机器人被生产出来的时候
            # 机器人人口增加
            Robot.population += 1
    
        def die(self):
            """啊!我要死掉了。"""
            print("{} is being destroyed!".format(self.name))
    
            Robot.population -= 1
    
            if Robot.population == 0:
                print("{} was the last one.".format(self.name))
            else:
                print("There are still {:d} robots working.".format(
                    Robot.population))
    
        def say_hi(self):
            """来自机器人的问候
    
            是的,他们有这种功能"""
            print("Greetings, my masters call me {}.".format(self.name))
    
        @classmethod	#	 装饰器,类方法
        def how_many(cls):
            """显示当前人口数。"""
            print("We have {:d} robots.".format(cls.population))
    
    droid1 = Robot("R2-D2")
    droid1.say_hi()
    Robot.how_many()
    
    droid2 = Robot("C-3PO")
    droid2.say_hi()
    Robot.how_many()
    
    print("\nRobots can do some work here.\n")
    
    print("Robots have finished their work. So let's destroy them.")
    droid1.die()
    droid2.die()
    
    Robot.how_many()
    
  • 继承

    class SchoolMember:
        '''代表了学校中的任何一个成员'''
        def __init__(self, name, age):
            self.name = name
            self.age = age
            print('(Initialized SchoolMember: {})'.format(self.name))
    
        def tell(self):
            '''告诉我细节'''
            print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")
    
    class Teacher(SchoolMember):
        '''表征一个老师'''
        def __init__(self, name, age, salary):
            SchoolMember.__init__(self, name, age)
            self.salary = salary
            print('(Initialized Teacher: {})'.format(self.name))
    
        def tell(self):
            SchoolMember.tell(self)
            print('Salary: "{:d}"'.format(self.salary))
    
    class Student(SchoolMember):
        '''表征一个学生'''
        def __init__(self, name, age, marks):
            SchoolMember.__init__(self, name, age)
            self.marks = marks
            print('(Initialized Student: {})'.format(self.name))
    
        def tell(self):
            SchoolMember.tell(self)
            print('Marks: "{:d}"'.format(self.marks))
    
    t = Teacher('Mrs. Shrividya', 40, 30000)
    s = Student('Swaroop', 25, 75)
    
    # 输出一个空行
    print()
    
    members = [t, s]
    for member in members:
        # 所有的老师和学生都可用
        member.tell()
    

    输出

    (Initialized SchoolMember: Mrs. Shrividya)
    (Initialized Teacher: Mrs. Shrividya)
    (Initialized SchoolMember: Swaroop)
    (Initialized Student: Swaroop)
    
    Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
    Name:"Swaroop" Age:"25" Marks: "75"
    

输入与输出

  • poem = '''\
    Programming is fun
    When the work is done
    if you wanna make your work also fun:
        use Python!
    '''
    
    # 打开文件进行 'w'riting 写操作
    f = open('poem.txt', 'w')
    # 将文本写入到文件
    f.write(poem)
    # 关闭文件
    f.close()
    
    # 如果没有指定文件打开方式
    # 默认使用 'r'ead 读模式
    f = open('poem.txt')
    while True:
        line = f.readline()
        # 零行意味着 EOF 文件结尾
        if len(line) == 0:
            break
        # `line` 中已经自带换行了
        # 因为它是从文件中读取出来的
        print(line, end='')
    # 关闭文件
    f.close()
    
  • Pickle

    import pickle
    
    # 这里我们将存储对象的文件的名称
    shoplistfile = 'shoplist.data'
    # 要买的东西的清单
    shoplist = ['apple', 'mango', 'carrot']
    
    # 写入文件
    f = open(shoplistfile, 'wb')
    # 将对象存储到文件
    pickle.dump(shoplist, f)
    f.close()
    
    # 销毁 shoplist 变量
    del shoplist
    
    # 从存储中读回
    f = open(shoplistfile, 'rb')
    # 从文件加载对象
    storedlist = pickle.load(f)
    print(storedlist)
    
  • Unicode

    # encoding=utf-8
    import io
    
    f = io.open("abc.txt", "wt", encoding="utf-8")
    f.write(u"Imagine non-English language here")
    f.close()
    
    text = io.open("abc.txt", encoding="utf-8").read()
    print(text)
    

异常

  • try..except,语句块关联的 else 子句, else 子句在没有错误发生时将会执行。

    class ShortInputException(Exception):
        '''用户定义的异常对象'''
        def __init__(self, length, atleast):
            Exception.__init__(self)
            self.length = length
            self.atleast = atleast
    
    try:
        text = input('Enter something --> ')
        if len(text) < 3:
            raise ShortInputException(len(text), 3)
        # 其他程序可以在这里正常执行
    except EOFError:
        print('Why did you do an EOF on me?')
    except ShortInputException as ex:
        print(('ShortInputException: The input was ' +
               '{0} long, expected at least {1}')
              .format(ex.length, ex.atleast))
    else:
        print('No exception was raised.')
    

    except 子句中,错误的类通过 as 把错误或异常对应的对象储存到了命名的变量中。

  • try…finally,无论是否异常,finally语句始终被执行

    读取一个文件。如何保证无论是否引发错误,文件对象都被正确关闭? 可以使用 finally 语句块来完成。

    import sys
    import time
    
    f = None
    try:
        f = open("poem.txt")
        # 我们通常读取文件的语句
        while True:
            line = f.readline()
            if len(line) == 0:
                break
            print(line, end='')
            sys.stdout.flush()
            print("Press ctrl+c now")
            # 让程序保持运行一段时间
            time.sleep(2)
    except IOError:
        print("Could not find file poem.txt")
    except KeyboardInterrupt:
        print("!! You cancelled the reading from the file.")
    finally:
        if f:
            f.close()
        print("(Cleaning up: Closed the file)")
    
  • withwith open 自动完成文件关闭,

    with open("poem.txt") as f:
        for line in f:
            print(line, end='')
    

更多知识

  • sys模块sys.argv 列表包含了命令行参数,当前路径。sys.version_infopython版本

  • 传递元组

    注意, a, b = <某些表达式> 会将表达式的结果解析为两个值组成的元组。

    >>> def get_error_details():
    ...     return (2, 'details')
    ...
    >>>errnum, errstr = get_error_details()
    >>>errnum
    2
    >>>errstr
    'details'
    

    Python 中交换两个变量的最快方法,a, b = b, a

  • 魔术方法

    __init__(self, ...),创建新对象会使用此方法

    __del__(self),在对象被销毁之前调用(具有不可预测时机,所以避免使用它)

    __str__(self),当我们使用 print 函数或使用 str() 时调用

    __lt__(self, other),使用小于运算符(<)时调用。 所有运算符都有特殊的方法(+,> 等)

    __getitem__(self, key),使用 x[key] 索引操作时调用。

    __len__(self),当内置的 len() 函数用于序列对象时调用。

  • 单个语句块,语句块只包含一个语句,可以在条件语句或循环语句的同一行上指定它

    flag = True
    if flag: print('Yes')
    

    注意,这样可以使你的程序更小,但不推荐

  • Lambda格式,创建新的函数对象,采用一个参数,后跟一个表达式,返回此表达式的值

    points = [{'x': 2, 'y': 3},
              {'x': 4, 'y': 1}]
    points.sort(key=lambda i: i['y'])
    print(points)   # [{'x': 4, 'y': 1}, {'x': 2, 'y': 3}]
    
  • 列表推导,用于从现有列表中导出新列表,
    有一个数字列表,获得一个相应的新列表,其中所有数字仅在数字本身大于 2 时乘以 2。

    listone = [2, 3, 4]
    listtwo = [2*i for i in listone if i > 2]
    print(listtwo)
    
  • 在函数中接受元组和字典,使用 *** 前缀将参数作为元组或字典接收到函数中,

    def powersum(power, *args):
    	'''返回每个参数指定幂次的总和。'''
    	total = 0
    	for i in args:
            total += pow(i, power)
            return total	
        powersum(2, 3, 4)	# 25
        powersum(2, 10)		# 100
    

    args变量上有一个*前缀,所有传递给函数的额外参数都作为元组存储在args中。 如果使用了**前缀,那么额外的参数将被认为是字典的键/值对。

  • assert,断言某值为 True,不是 True 则引发错误

    >>>mylist = ['item']
    >>>assert len(mylist) >= 1
    >>>mylist.pop()
    'item'
    >>>assert len(mylist) >= 1
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AssertionError
    
  • 装饰器,用于包装函数的快捷方式。

posted @ 2022-09-12 14:41  小林の一生  阅读(20)  评论(0)    收藏  举报