切片对象
sequence[起始索引 : 结束索引 : 步进值]
>>> f='abcde'
>>> f[::-1]
'edcba'
>>> f[::-2]
'eca'
>>> f[::-1]
'edcba'
>>> f[::-2]
'eca'
对象身份比较
每个对象都有一个计数器,记录它自己的引用次数。
is 和is not运算符来测试两个变量是否指向同一个对象。
>>> a=2
>>> b=3
>>> a is b
False
>>> b=3
>>> a is b
False
>>> a is not b
True
True
>>> id(a)==id(b)
整数对象和字符串对象是不可变对象,所以Python 会很高效的缓存它们。
布尔类型
Python 支持一个表达式进行多种比较操作, 其实这个表达式本质上是由多个隐式的 and 连接起来。
标准类型内建函数
cmp(), str(), type(), repr()=
单反引号(``) 运算符
>>> cmp(a,b)
0
>>> repr(a)
'2'
>>> str(b)
'2'
>>> type(b)
<type 'int'>
0
>>> repr(a)
'2'
>>> str(b)
'2'
>>> type(b)
<type 'int'>
>>> type(type(4))
<type 'type'>
<type 'type'>
str()函数得到的字符串可读性好, 而repr()函数得到的字符串通常可以用来重新获得该对象, 通常情况下 obj == eval(repr(obj)) 这个等式是成立的。
>>> b==eval(repr(b))
True
True
>>> '(4.53-2j)'
'(4.53-2j)'
'(4.53-2j)'
type()
>>> class Foo:pass
...
>>> foo=Foo()
>>> class Bar(object):pass
...
>>> bar=Bar()
>>> type(Foo)
<type 'classobj'>
>>> type(foo)
<type 'instance'>
>>> type(Bar)
<type 'type'>
>>> type(bar)
<class '__main__.Bar'>
...
>>> foo=Foo()
>>> class Bar(object):pass
...
>>> bar=Bar()
>>> type(Foo)
<type 'classobj'>
>>> type(foo)
<type 'instance'>
>>> type(Bar)
<type 'type'>
>>> type(bar)
<class '__main__.Bar'>
isinstance()
#! /usr/bin/python
def dis(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!'
dis(-69)
dis(9999999999999999999999L)
dis(98.6)
dis(-5.2+1.9j)
dis('xxx')
def dis(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!'
dis(-69)
dis(9999999999999999999999L)
dis(98.6)
dis(-5.2+1.9j)
dis('xxx')
>>> import types
>>> if type(num)==types.IntType:
>>> from types import IntType
>>> if type(num) is IntType:
>>> if type(num) is IntType:
类型工厂函数
Python 2.2 统一了类型和类, 所有的内建类型现在也都是类
int(), long(), float(), complex()
str(), unicode(), basestring()
list(), tuple()
type()
str(), unicode(), basestring()
list(), tuple()
type()