您的位置:首页 > 编程语言 > Python开发

Python语法(二)

2014-03-07 20:22 141 查看

Dictionaries

类似于Perl中的哈希

like associative arrays or hashes in Perl;

key-value pairs

>>> aDict = {'host': 'earth'} # create dict

>>> aDict['port'] = 80 # add to dict

>>> aDict

{'host': 'earth', 'port': 80}

>>> aDict.keys()

['host', 'port']

>>> aDict['host']

'earth'

>>> for key in aDict:

... print key, aDict[key]

...

host earth

port 80

Indentation

代码块通过缩进来识别

identified by indentation

Contral Statements

if expression1:

if_suite

elif expression2:

elif_suite

else:

else_suite
while expression:

while_suite
>>> foo = 'abc'

>>> for c in foo:

... print c

...

a

b

c
Python provides the range() built-in function to generate

such a list for us. It does exactly what we want, taking

a range of numbers and

generating a list.

>>> for eachNum in range(3):

... print eachNum

...

0

1

2

List Compression

列表解析

>>> squared = [x ** 2 for x in range(4)]

>>> sqdEvens = [x ** 2 for x in range(8) if not x % 2]

open() and file()

打开文件 handle = open(file_name, access_mode = 'r')

access_mode is either 'r' for read, 'w' for write, or 'a'

for append,'+' for dual read-write access and the 'b'

for binary access. default of read-only ('r')

#读取整个文件 因为文件中的每行文本已经自带了换行字符,所以要

抑制print 语句产生的换行符号

filename = raw_input('Enter file name: ')

fobj = open(filename, 'r')

for eachLine in fobj:

print eachLine,

fobj.close()

#file()内建函数,功能等同于open()



Errors and Exceptions

错误检测及异常处理

try:

filename = raw_input('Enter file name: ')

fobj = open(filename, 'r')

for eachLine in fobj:

print eachLine,

fobj.close()

except IOError, e:

print 'file open error:', e



Function

函数

定义函数

def function_name([arguments]):

"optional documentation string"

function_suite

调用函数

>>> addMe2Me([-1, 'abc'])

[-1, 'abc', -1, 'abc']

定义类

class ClassName(base_class[es]):

"optional documentation string"

static_member_declarations

method_declarations

__init__() 方法有一个特殊名字, 所有名字开始和结束都有两个下划线的方法都是特殊方法。当一个类实例被创建时, __init__() 方法会自动执行, 在类实例创建完毕后执行, 类似构建函数。__init__() 可以被当成构建函数, 不过不象其它语言中的构建函数, 它并不创建实例--它仅仅是你的对象创建后执行的第一个方法。它的目的是执行一些该对象的必要的初始化工作。通过创建自己的 __init__() 方法, 你可以覆盖默认的 __init__()方法(默认的方法什么也不做),从而能够修饰刚刚创建的对象。在这个例子里,
我们初始化了一个名为 name的类实例属性(或者说成员)。这个变量仅在类实例中存在, 它并不是实际类本身的一部分。__init__()需要一个默认的参数, 前一节中曾经介绍过。毫无疑问,你也注意到每个方法都有

的一个参数, self.什么是 self ? 它是类实例自身的引用。其他语言通常使用一个名为 this 的标识符。

如何创建类实例

>>> foo1 = FooClass()

Created a class instance for John Doe

self.__class__.__name__ 这个变量表示实例化它的类的名字。

模块

模块是一种组织形式, 它将彼此有关系的Python 代码组织到一个个独立文件当中。模块可以包含可执行代码, 函数和类或者这些东西的组合。当你创建了一个 Python 源文件,模块的名字就是不带 .py 后缀的文件名。

>>> import sys

>>> sys.stdout.write('Hello World!\n')

Hello World!

PEP 就是一个 Python 增强提案(Python Enhancement Proposal)

Python 的创始人, Guido van Rossum(Python 终身的仁慈的独裁者)

实用内建函数

Function Description

dir([obj]) Display attributes of object or the names of global variables if no parameter given

help([obj]) Display object’s documentation string in a pretty-printedformat or enters interactive help if no parameter given

int(obj) Convert object to an integer

len(obj) Return length of object

open(fn, mode) Open file fn with mode ('r' = read, 'w' = write)

range([[start,

]stop[,step]) Return a list of integers that begin at start up tobut not including stop in increments of step; start defaults to 0, and step defaults to 1

raw_input(str) Wait for text input from the user, optional prompt string can be provided

str(obj) Convert object to a string

type(obj) Return type of object (a type object itself!)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: