python核心编程第二版

python核心编程第二版:第四章--对象

2016-08-08  本文已影响27人  Bioconductor

4.1 对象

三个特性:身份、类型、值

身份:

每个对象都有唯一的身份来标识自己,使用内建函数id()得到。

例子

#!/usr/bin/env python
#coding:utf-8

a=32;
print a
b = a ;
print id(a),id(b)

结果:

D:\python27\python.exe E:/workp/python/ex4.py
32
36402460 36402460

类型:

决定了该对象可以保存什么类型的值,可以进行什么样的操作,遵循什么样的规则。用内建函数type()查看。类型也是对象

#!/usr/bin/env python
#coding:utf-8

a=32;
print a
b = a ;
print id(a),id(b)
c=type(a)
d=type(id(a))
e=id(d) #类型也是对象
print c,d,e

结果:

D:\python27\python.exe E:/workp/python/ex4.py
32
37188892 37188892
<type 'int'> <type 'int'> 505557880

值:

对象表示的数据项

4.2 标准类型

4.3 其他内建类型

4.3.1 类型对象和type类型对象

type() 得到特定对象的类型信息

例子

#!/usr/bin/env python
#coding:utf8
a=12
print type(a)
print type(type(a)) #类型对象的类型

结果:

<type 'int'>
<type 'type'>

4.4 切片对象

例子

#!/usr/bin/env python
#coding:utf8
foostr='abcde'
print foostr[::-1] #颠倒
print foostr[1::-1] #起始为1,步长为-1,逆向
print foostr[::-2] #逆向,步长为2

结果:

edcba
ba
eca

函数

xrange与range比较

1、 输出

a=xrange(0,8,2)
b=range(0,8,2)
print a,b

结果:

xrange(0, 8, 2) [0, 2, 4, 6]
c=list(xrange(0,8,2))
print c

结果:

[0, 2, 4, 6]

2、for

for i in xrange(6):
    print i,

for j in range(6):
    print j,

结果:

0 1 2 3 4 5 
0 1 2 3 4 5

3、输出的类型

print type(i),type(j)

结果:

<type 'int'> <type 'int'>

xrange每次返回一个值,有大量数据时使用xrange比range好

4.5.3 布尔类型

4.6 标准内建函数

cmp(i,j)   
i<j  -1
i>j  1
i=j  0
a=3
b=2
print cmp(a,b)

结果:

1
a=324
print type(a)

结果:

<type 'int'>

访问模式

这里写图片描述
上一篇 下一篇

猜你喜欢

热点阅读