Python学习笔记

一、《简明Python教程》例子

http://woodpecker.org.cn/abyteofpython_cn/chinese/ch12.html 5.  运算符与表达式
简介
运算符
运算符优先级
      计算顺序
      结合规律
表达式
      使用表达式
概括
6.  控制流
简介
if语句
      使用if语句
      它如何工作
while语句
      使用while语句
for循环
      使用for语句
break语句
      使用break语句
continue语句
      使用continue语句
概括
7.  函数
简介
      定义函数
函数形参
      使用函数形参
局部变量
      使用局部变量
      使用global语句
默认参数值
      使用默认参数值
关键参数
      使用关键参数
return语句
      使用字面意义上的语句
DocStrings
      使用DocStrings
概括
8.  模块
简介
      使用sys模块
字节编译的.pyc文件
from..import语句
模块的__name__
      使用模块的__name__
制造你自己的模块
      创建你自己的模块
      from..import
dir()函数
      使用dir函数
概括
9.  数据结构
简介
列表
      对象与类的快速入门
      使用列表
元组
      使用元组
      元组与打印语句
字典
      使用字典
序列
      使用序列
参考
      对象与参考
更多字符串的内容
      字符串的方法
概括
10.  解决问题——编写一个Python脚本
问题
解决方案
      版本一
      版本二
      版本三
      版本四
      进一步优化
软件开发过程
概括
11.  面向对象的编程
简介
self
      创建一个类
对象的方法
      使用对象的方法
__init__方法
      使用__init__方法
类与对象的变量
      使用类与对象的变量
继承

                   使用继承

12. 输入/输出

文件
      使用文件
储存器
      储存与取储存
概括

14.  Python标准库
简介
sys模块
      命令行参数
      更多sys的内容
os模块
概括
15.  更多Python的内容
特殊的方法
单语句块
列表综合
      使用列表综合
在函数中接收元组和列表
lambda形式
      使用lambda形式
exec和eval语句
assert语句
repr函数
概括


获取帮助:

    >>> help('print')


例5.1

#!/usr/bin/python
# Filename: expression.py


length = 5
breadth = 2
area = length * breadth
print 'Area is', area
print 'Perimeter is'* (length + breadth)


例6.1

#!/usr/bin/python
# Filename: if.py 


number = 23
guess = int(raw_input('Enter an integer : '))

if guess == number:
    print 'Congratulations, you guessed it.' # New block starts here
    print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
    print 'No, it is a little higher than that' # Another block
    # You can do whatever you want in a block ...
else:
    print 'No, it is a little lower than that' 
    # you must have guess > number to reach here

print 'Done'
# This last statement is always executed, after the if statement is executed


例6.2

#!/usr/bin/python
# Filename: while.py


number = 23
running = True

while running:
    guess = int(raw_input('Enter an integer : '))

    if guess == number:
        print 'Congratulations, you guessed it.' 
        running = False # this causes the while loop to stop
    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.' 
    # Do anything else you want to do here

print 'Done'


例6.3

#!/usr/bin/python
# Filename: for.py


for in range(15):
    print i
else:
    print 'The for loop is over'

 

例子6.4

#!/usr/bin/python
# Filename: break.py

while True:
    s = raw_input('Enter something : ')
    if s == 'quit':
        break
    print 'Length of the string is'len(s)
print 'Done'


例子6.5

#!/usr/bin/python
# Filename: continue.py


while True:
    s = raw_input('Enter something : ')
    if s == 'quit':
        break
    if len(s) < 3:
        continue
    print 'Input is of sufficient length'
    # Do other kinds of processing here...


例7.1

#!/usr/bin/python
# Filename: function1.py


def sayHello():
    print 'Hello World!' # block belonging to the function

sayHello() # call the function


例7.2

#!/usr/bin/python
# Filename: func_param.py


def printMax(a, b):
    if a > b:
        print a, 'is maximum'
    else:
        print b, 'is maximum'

printMax(34# directly give literal values

x = 5
y = 7

printMax(x, y) # give variables as arguments


例7.3 使用局部变量

#!/usr/bin/python
# Filename: func_local.py


def func(x):
    print 'x is', x
    x = 2
    print 'Changed local x to', x

x = 50
func(x)
print 'x is still', x


例7.4 使用global语句

#!/usr/bin/python
# Filename: func_global.py


def func():
    global x

    print 'x is', x
    x = 2
    print 'Changed local x to', x

x = 50
func()
print 'Value of x is', x


例7.5 使用默认参数值

#!/usr/bin/python
# Filename: func_default.py


def say(message, times = 1):
    print message * times

say('Hello')
say('World'5)


例7.6 使用关键参数

#!/usr/bin/python
# Filename: func_key.py


def func(a, b=5, c=10):
    print 'a is', a, 'and b is', b, 'and c is', c

func(37)
func(25, c=24)
func(c=50, a=100)


例7.7  return语句

#!/usr/bin/python
# Filename: func_return.py


def maximum(x, y):
    if x > y:
        return x
    else:
        return y

print maximum(23)


注意,没有返回值的return语句等价于return NoneNone是Python中表示没有任何东西的特殊类型。例如,如果一个变量的值为None,可以表示它没有值。

除非你提供你自己的return语句,每个函数都在结尾暗含有return None语句。通过运行print someFunction(),你可以明白这一点,函数someFunction没有使用return语句,如同:

def  someFunction ():
    pass

pass语句在Python中表示一个空的语句块。


例8.1 使用sys模块

#!/usr/bin/python
# Filename: using_sys.py


import sys

print 'The command line arguments are:'
for in sys.argv:
    print i

print '\n\nThe PYTHONPATH is'sys.path, '\n'


例9.1  使用列表

#!/usr/bin/python
# Filename: using_list.py

# This is my shopping list

shoplist = ['apple''mango''carrot''banana']

print 'I have'len(shoplist),'items to purchase.'

print 'These items are:'# Notice the comma at end of the line
for item in shoplist:
    print item,

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就知道你是在指明一个列表。一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项目。由于你可以增加或删除项目,我们说列表是可变的 数据类型,即这种类型是可以被改变的。


例9.2  使用元组

#!/usr/bin/python
# Filename: using_tuple.py


zoo = ('wolf''elephant''penguin')
print 'Number of animals in the zoo is'len(zoo)

new_zoo = ('monkey''dolphin', zoo)
print 'Number of animals 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]


元组和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。


例9.3  使用元组输出

#!/usr/bin/python
# Filename: print_tuple.py


age = 22
name = 'Swaroop'

print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name


例9.4  使用字典

#!/usr/bin/python
# Filename: using_dict.py

# 'ab' is short for 'a'ddress'b'ook


ab = {       'Swaroop'   'swaroopch@byteofpython.info',
             'Larry'     'larry@wall.org',
             'Matsumoto' 'matz@ruby-lang.org',
             'Spammer'   'spammer@hotmail.com'
     }

print "Swaroop's address is %s" % ab['Swaroop']

# Adding a key/value pair
ab['Guido'] = 'guido@python.org'

# Deleting a key/value pair
del ab['Spammer']

print '\nThere are %d contacts in the address-book\n' len(ab)
for name, address in ab.items():
    print 'Contact %s at %s' % (name, address)

if 'Guido' in ab: # OR ab.has_key('Guido')
    print "\nGuido's address is %s" % ab['Guido']


注意,你只能使用不可变的对象(比如字符串)来作为字典的键,但是你可以不可变或可变的对象作为字典的值。基本说来就是,你应该只使用简单的对象作为键。

键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。

记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。

字典是dict类的实例/对象。


例9.5 序列

#!/usr/bin/python
# Filename: seq.py


shoplist = ['apple''mango''carrot''banana']

# Indexing or 'Subscription' operation
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]

# Slicing on a list
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[:]

# Slicing on a string
name = 'swaroop'
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[:]


列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。

索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的。因此,shoplist[-1]表示序列的最后一个元素而shoplist[-2]抓取序列的倒数第二个项目。

切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。注意这与你使用的索引操作符十分相似。记住数是可选的,而冒号是必须的。

切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。如果不指定第一个数,Python就从序列首开始。如果没有指定第二个数,则Python会停止在序列尾。注意,返回的序列从开始位置 开始 ,刚好在 结束 位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。


例9.6  对象与参考

#!/usr/bin/python
# Filename: reference.py


print 'Simple Assignment'
shoplist = ['apple''mango''carrot''banana']
mylist = shoplist # mylist is just another name pointing to the same object!

del shoplist[0]

print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object


print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0# remove first item

print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different

当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 参考 那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定

大多数解释已经在程序的注释中了。你需要记住的只是如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都 参考 同一个对象,那么如果你不小心的话,可能会引来各种麻烦。


例9.7  字符串的方法

#!/usr/bin/python
# Filename: str_methods.py


name = 'Swaroop' # This is a string object 

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)


例10.1 备份脚本——版本1

#!/usr/bin/python
# Filename: backup_ver1.py


import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte''/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that

# 2. The backup must be stored in a main backup directory

target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using

# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time

target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'

# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))

# Run the backup
if os.system(zip_command) == 0:
    print 'Successful backup to', target
else:
    print 'Backup FAILED'


例10.2  备份脚本——版本2

#!/usr/bin/python
# Filename: backup_ver2.py


import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte''/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that

# 2. The backup must be stored in a main backup directory

target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using

# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory

today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')

# Create the subdirectory if it isn't already there
if not os.path.exists(today):
    os.mkdir(today) # make directory
    print 'Successfully created directory', today

# The name of the zip file
target = today + os.sep + now + '.zip'

# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))

# Run the backup
if os.system(zip_command) == 0:
    print 'Successful backup to', target
else:
    print 'Backup FAILED'


例10.4 备份脚本——版本四

#!/usr/bin/python
# Filename: backup_ver4.py


import os
import time

# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte''/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that

# 2. The backup must be stored in a main backup directory

target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using

# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory

today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')

# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment --> ')
if len(comment) == 0# check if a comment was entered
    target = today + os.sep + now + '.zip'
else:
    target = today + os.sep + now + '_' + \
        comment.replace(' ''_') + '.zip'
    # Notice the backslash!

# Create the subdirectory if it isn't already there
if not os.path.exists(today):
    os.mkdir(today) # make directory
    print 'Successfully created directory', today

# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))

# Run the backup
if os.system(zip_command) == 0:
    print 'Successful backup to', target
else:
    print 'Backup FAILED'


例11.1 创建一个类

#!/usr/bin/python
# Filename: simplestclass.py


class Person:
    pass # An empty block

p = Person()
print p


例11.2 使用对象的方法

#!/usr/bin/python
# Filename: method.py


class Person:
    def sayHi(self):
        print 'Hello, how are you?'

p = Person()
p.sayHi()


# This short example can also be written as Person().sayHi()


例11.3 使用__init__方法

#!/usr/bin/python
# Filename: class_init.py


class Person:
    def __init__(self, name):
        self.name = name

    def sayHi(self):
        print 'Hello, my name is', self.name

p = Person('Swaroop')
p.sayHi()


# This short example can also be written as Person('Swaroop').sayHi()


__init__方法在类的一个对象被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的 初始化 。注意,这个名称的开始和结尾都是双下划线。


例11.4 使用类与对象的变量

#!/usr/bin/python
# Filename: objvar.py


class Person:
    '''Represents a person.'''
    population = 0

    def __init__(self, name):
        '''Initializes the person's data.'''
        self.name = name
        print '(Initializing %s)' % self.name

        # When this person is created, he/she
        # adds to the population

        Person.population += 1

    def __del__(self):
        '''I am dying.'''
        print '%s says bye.' % self.name

        Person.population -= 1

        if Person.population == 0:
            print 'I am the last one.'
        else:
            print 'There are still %d people left.' % Person.population

    def sayHi(self):
        '''Greeting by the person.

        Really, that's all it does.'''

        print 'Hi, my name is %s.' % self.name

    def howMany(self):
        '''Prints the current population.'''
        if Person.population == 1:
            print 'I am the only person here.'
        else:
            print 'We have %d persons here.' % Person.population

swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

kalam = Person(
'Abdul Kalam')
kalam.sayHi()
kalam.howMany()

有两种类型的  ——类的变量和对象的变量,它们根据是类还是对象 拥有 这个变量而区分

这是一个很长的例子,但是它有助于说明类与对象的变量的本质。这里,population属于Person类,因此是一个类的变量。name变量属于对象(它使用self赋值)因此是对象的变量。

观察可以发现__init__方法用一个名字来初始化Person实例。在这个方法中,我们让population增加1,这是因为我们增加了一个人。同样可以发现,self.name的值根据每个对象指定,这表明了它作为对象的变量的本质。

记住,你能使用self变量来参考同一个对象的变量和方法。这被称为 属性参考 。

在这个程序中,我们还看到docstring对于类和方法同样有用。我们可以在运行时使用Person.__doc__Person.sayHi.__doc__来分别访问类与方法的文档字符串。

就如同__init__方法一样,还有一个特殊的方法__del__,它在对象消逝的时候被调用。对象消逝即对象不再被使用,它所占用的内存将返回给系统作它用。在这个方法里面,我们只是简单地把Person.population1

当对象不再被使用时,__del__方法运行,但是很难保证这个方法究竟在 什么时候 运行。如果你想要指明它的运行,你就得使用del语句,就如同我们在以前的例子中使用的那样。


例11.5 使用继承

#!/usr/bin/python
# Filename: inherit.py


class SchoolMember:
    '''Represents any school member.'''
    def __init__(self, name, age):
        self.name = name
        self.age = age

        print '(Initialized SchoolMember: %s)' % self.name

    def tell(self):
        '''Tell my details.'''
        print 'Name:"%s" Age:"%s"' % (self.name, self.age),

class Teacher(SchoolMember):
    '''Represents a teacher.'''
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)
        self.salary = salary

        print '(Initialized Teacher: %s)' % self.name

    def tell(self):
        SchoolMember.tell(self)

        print 'Salary: "%d"' % self.salary

class Student(SchoolMember):
    '''Represents a student.'''
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)
        self.marks = marks

        print '(Initialized Student: %s)' % self.name

    def tell(self):
        SchoolMember.tell(self)

        print 'Marks: "%d"' % self.marks

t = Teacher(
'Mrs. Shrividya'4030000)
s = Student(
'Swaroop'2275)

print # prints a blank line

members = [t, s]
for member in members:
    member.tell() 
# works for both Teachers and Students


例12.1 使用文件

#!/usr/bin/python
# Filename: using_file.py


poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!
'''


f = file('poem.txt''w'# open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
    line = f.readline()

    if len(line) == 0# Zero length indicates EOF
        break
    print line,
    # Notice comma to avoid automatic newline added by Python
f.close() # close the file


你可以通过创建一个file类的对象来打开一个文件,分别使用file类的readreadlinewrite方法来恰当地读写文件。对文件的读写能力依赖于你在打开文件时指定的模式。最后,当你完成对文件的操作的时候,你调用close方法来告诉Python我们完成了对文件的使用。

首先,我们通过指明我们希望打开的文件和模式来创建一个file类的实例。模式可以为读模式('r')、写模式('w')或追加模式('a')。事实上还有多得多的模式可以使用,你可以使用help(file)来了解它们的详情。

我们首先用写模式打开文件,然后使用file类的write方法来写文件,最后我们用close关闭这个文件。

接下来,我们再一次打开同一个文件来读文件。如果我们没有指定模式,读模式会作为默认的模式。在一个循环中,我们使用readline方法读文件的每一行。这个方法返回包括行末换行符的一个完整行。所以,当一个 空的 字符串被返回的时候,即表示文件末已经到达了,于是我们停止循环。

注意,因为从文件读到的内容已经以换行符结尾,所以我们在print语句上使用逗号来消除自动换行。最后,我们用close关闭这个文件。


例12.2 储存与取储存

#!/usr/bin/python
# Filename: pickling.py


import cPickle as p
#import pickle as p

shoplistfile = 'shoplist.data'
# the name of the file where we will store the object

shoplist = ['apple''mango''carrot']

# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) 
# dump the object to a file
f.close()

del shoplist # remove the shoplist

# Read back from the storage

f = file(shoplistfile)
storedlist = p.load(f)

print storedlist


Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。

还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。

首先,请注意我们使用了import..as语法。这是一种便利方法,以便于我们可以使用更短的模块名称。在这个例子中,它还让我们能够通过简单地改变一行就切换到另一个模块(cPickle或者pickle)!在程序的其余部分的时候,我们简单地把这个模块称为p

为了在文件里储存一个对象,首先以写模式打开一个file对象,然后调用储存器模块的dump函数,把对象储存到打开的文件中。这个过程称为 储存 。

接下来,我们使用pickle模块的load函数的返回来取回对象。这个过程称为 取储存 。


例14.1 使用sys.argv

#!/usr/bin/python
# Filename: cat.py


import sys

def readfile(filename):
    '''Print a file to the standard output.'''
    f = file(filename)
    while True:
        line = f.readline()

        if len(line) == 0:
            break
        print line, # notice comma
    f.close()

# Script starts from here
if len(sys.argv) < 2:
    print 'No action specified.'
    sys.exit()

if sys.argv[1].startswith('--'):
    option = sys.argv[1][2:]
    # fetch sys.argv[1] but without the first two characters
    if option == 'version':
        print 'Version 1.2'
    elif option == 'help':
        print '''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
  --version : Prints the version number
  --help    : Display this help'''

    else:
        print 'Unknown option.'
    sys.exit()
else:
    for filename in sys.argv[1:]:
        readfile(filename)


输出:

$ python cat.py
No action specified.

$ python cat.py --help
This program prints files to the standard output.
Any number of files can be specified.
Options include:
  --version : Prints the version number
  --help    : Display this help

$ python cat.py --version
Version 1.2

$ python cat.py --nonsense
Unknown option.

$ python cat.py poem.txt
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!


在Python程序运行的时候,即不是在交互模式下,在sys.argv列表中总是至少有一个项目。它就是当前运行的程序名称,作为sys.argv[0](由于Python从0开始计数)。其他的命令行参数在这个项目之后。

sys模块中其他令人感兴趣的项目有sys.stdinsys.stdoutsys.stderr它们分别对应你的程序的标准输入、标准输出和标准错误流。



os模块

这个模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行。一个例子就是使用os.sep可以取代操作系统特定的路径分割符。

下面列出了一些在os模块中比较有用的部分。它们中的大多数都简单明了。

  • os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'

  • os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。

  • os.getenv()os.putenv()函数分别用来读取和设置环境变量。

  • os.listdir()返回指定目录下的所有文件和目录名。

  • os.remove()函数用来删除一个文件。

  • os.system()函数用来运行shell命令。

  • os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'

  • os.path.split()函数返回一个路径的目录名和文件名。

            >>> os.path.split('/home/swaroop/byte/code/poem.txt')
         ('/home/swaroop/byte/code', 'poem.txt')

  • os.path.isfile()os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.path.existe()函数用来检验给出的路径是否真地存在。

你可以利用Python标准文档去探索更多有关这些函数和变量的详细知识。你也可以使用help(sys)等等。



特殊方法

在类中有一些特殊的方法具有特殊的意义,比如__init____del__方法,它们的重要性我们已经学习过了。

一般说来,特殊的方法都被用来模仿某个行为。例如,如果你想要为你的类使用x[key]这样的索引操作(就像列表和元组一样),那么你只需要实现__getitem__()方法就可以了。想一下,Python就是对list类这样做的!

下面这个表中列出了一些有用的特殊方法。如果你想要知道所有的特殊方法,你可以在《Python参考手册》中找到一个庞大的列表。

名称说明
__init__(self,...)这个方法在新建对象恰好要被返回使用之前被调用。
__del__(self)恰好在对象要被删除之前调用。
__str__(self)在我们对对象使用print语句或是使用str()的时候调用。
__lt__(self,other)当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。
__getitem__(self,key)使用x[key]索引操作符的时候调用。
__len__(self)对序列对象使用内建的len()函数的时候调用。


例15.1 使用列表综合

#!/usr/bin/python
# Filename: list_comprehension.py


listone = [234]
listtwo = [2*i for in listone if i > 2]
print listtwo


输出:

$ python list_comprehension.py
[6, 8]


例15.2 在函数中接收元组与列表

>>> def powersum(power, *args):
...     '''Return the sum of each argument raised to specified power.'''
...     total = 0
...     for i in args:
...          total += pow(i, power)
...     return total
...
>>> powersum(2, 3, 4)
25

>>> powersum(2, 10)
100


当要使函数接收元组或字典形式的参数的时候,有一种特殊的方法,它分别使用***前缀。这种方法在函数需要获取可变数量的参数的时候特别有用。

由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前缀,多余的参数则会被认为是一个字典的键/值对。



lamda形式

lambda语句被用来创建新的函数对象,并且在运行时返回它们。

#!/usr/bin/python
# Filename: lambda.py


def make_repeater(n):
    return lambda s: s*n

twice = make_repeater(
2)

print twice('word')
print twice(5)


$ python lambda.py
wordword
10


这里,我们使用了make_repeater函数在运行时创建新的函数对象,并且返回它。lambda语句用来创建函数对象。本质上,lambda需要一个参数,后面仅跟单个表达式作为函数体,而表达式的值被这个新建的函数返回。注意,即便是print语句也不能用在lambda形式中,只能使用表达式。


exec和eval语句

exec语句用来执行储存在字符串或文件中的Python语句。例如,我们可以在运行时生成一个包含Python代码的字符串,然后使用exec语句执行这些语句。下面是一个简单的例子。

>>> exec 'print "Hello World"'
Hello World

eval语句用来计算存储在字符串中的有效Python表达式。下面是一个简单的例子。

>>> eval('2*3')
6



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值