python 进阶学习之7

切片对象

sequence[起始索引 : 结束索引 : 步进值]
>>> f='abcde'
>>> f[::-1]
'edcba'
>>> f[::-2]
'eca'

对象身份比较

每个对象都有一个计数器,记录它自己的引用次数。
is 和is not运算符来测试两个变量是否指向同一个对象。
>>> a=2
>>> b=3
>>> a is b
False
>>> a is not b
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'>
>>> type(type(4))
<type 'type'>
str()函数得到的字符串可读性好, 而repr()函数得到的字符串通常可以用来重新获得该对象, 通常情况下 obj == eval(repr(obj)) 这个等式是成立的。
>>> b==eval(repr(b))
True
>>> '(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'>

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')
>>> import types
>>> if type(num)==types.IntType:
>>> from types import IntType
>>> if type(num) is IntType:

类型工厂函数

Python 2.2 统一了类型和类, 所有的内建类型现在也都是类
 int(), long(), float(), complex()
 str(), unicode(), basestring()
 list(), tuple()
 type()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值