1.1 python对象

    Python使用对象模型来存储数据。构造任何类型的值都是一个对象。

    Python对象拥有三个特性:身份、类型、值

    身份:每一个对象都有一个唯一的身份标识自己,任何对象的身份可以使用内建函数id()来得到。这个值可以被认为是该对象的内存地址。

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

    :对象表示的数据项。


1.2 标准类型

  • 数字

  • Integer    整型

  • Boolean    布尔型

  • Floating point real munber    浮点型

  • Complex number    复数型

  • String    字符串

  • List    列表

  • Tuple    元组

  • Dictionary    字典


1.3 其他内建类型

  • 类型

  • Null对象(None)

  • 文件

  • 集合/固定集合

  • 函数/方法

  • 模块


1.3.1 类型对象和type类型对象

>>> type(44)

>>> type(type(44))


1.3.2 布尔值

  • 空对象、值为零的任何数字或Null对象None的布尔值都是False:

    • None

    • False

    • 所有的值为零的数

    • 0(整型)

    • 0.0 (浮点型)

    • 0L (长整型)

    • 0.0+0.0j(复数)

    • ""(空字符串)

    • [] (空列表)

    • () (空元组)

    • {} (空字典)



1.4 内部类型

  • 代码

  • 跟踪记录

  • 切片

  • 省略

  • Xrange

1.4.1 代码对象

    代码对象是编译过的Python源代码片段,它是可执行对象。通过调用内建函数compile()可以得到代码对象。

1.4.2 帧对象

    帧对象表示Python的执行栈帧。帧对象包含Python解释器在运行时所需要知道的所有信息。

1.4.3 跟踪记录对象

1.4.4 切片对象

>>> foo = 'abcdef'
>>> foo[::-1]
'fedcba'
>>> foo[::]
'abcdef'
>>> foo[:3]
'abc'
>>> foo[1]
'b'
>>> foo[4:]
'ef'
>>> foo[::-2]
'fdb'>>> foolist = [123, 'aba', 12.31, 'abc']
>>> foolist[::-1]
['abc', 12.31, 'aba', 123]

1.4.5 省略对象

1.4.6 Xrange对象

    调用内建函数xrange()会生成一个Xrange对象,xrange()是内建函数range()的兄弟版本,用于需要节省内存使用或range()无法完成的超大数据集场合。


1.5 标准类型操作符


1.6 标准类型内建函数

1.6.1 type()

1.6.2 cmp()

>>> a, b = -4, 12
>>> cmp(a,b)    如果obj1小于obj2,则返回负整数
-1
>>> cmp(b,a)    如果obj1大于obj2,则返回正整型
1
>>> b = -4
>>> cmp(a,b)
0>>> a, b = 'abc', 'xyz' 
>>> cmp(a,b)
-1
>>> cmp(b,a)
1
>>> b = 'abc'
>>> cmp(a,b)
0

1.6.3 str()、repr()和``   ----对象的字符串表示

>>> str([0,5,9,9])
'[0, 5, 9, 9]'
>>> repr([0,5,9,9])
'[0, 5, 9, 9]'
>>> `([0,5,9,9])`
'[0, 5, 9, 9]'

1.6.4 type()和isinstance()

>>> type('')

>>> type([])

>>> type({})

>>> type(0L)

>>> type(1)

>>> type('a')

>>> type(())


1.6.5 检查类型(示例1)

[root@saltstack python]# cat typechk.py 
#!/usr/bin/pythondef displayNumType(num):print num, 'is',if isinstance(num, (int, long, float, complex)):print 'a number of type: ', type(num).__name__else:print 'not a number at all!!'
displayNumType(-69)
displayNumType(99999999999999999999L)
displayNumType(98.6)
displayNumType(-5.2+1.9j)
displayNumType('xxx')[root@saltstack python]# python typechk.py 
-69 is a number of type:  int
99999999999999999999 is a number of type:  long
98.6 is a number of type:  float
(-5.2+1.9j) is a number of type:  complex
xxx is not a number at all!!


1.6.6 例子进阶

#!/usr/bin/python
def displayNumType():print num, "is",if type(num) == type(0):print 'an integer'elif type(num) == type(0L):print 'a long'elif type(num) == type(0.0):print 'a float'elif type(num) == type(0+0j):print 'a complex number'else:print 'not a number at all!!'