Python入门篇之函数(2)
>>>print abs(-100)
100
>>>print abs(1+2j)
2.2360679775
2.callable(object)
callable()函数用于测试对象是否可调用,如果可以则返回1(真);否则返回0(假)。可调用对象包括函数、方法、代码对象、类和已经定义了“调用”方法的类实例。
>>> a="123"
>>> print callable(a)
0
>>> print callable(chr)
1
3.cmp(x,y)
cmp()函数比较x和y两个对象,并根据比较结果返回一个整数,如果x<y,则返回-1;如果x>y,则返回1,如果x==y则返回0。
>>>a=1
>>>b=2
>>>c=2
>>> print cmp(a,b)
-1
>>> print cmp(b,a)
1
>>> print cmp(b,c)
0
4.divmod(x,y)
divmod(x,y)函数完成除法运算,返回商和余数。
>>> divmod(10,3)
(3, 1)
>>> divmod(9,3)
(3, 0)
5.isinstance(object,class-or-type-or-tuple) -> bool
测试对象类型
>>> a='isinstance test'
>>> b=1234
>>> isinstance(a,str)
True
>>> isinstance(a,int)
False
>>> isinstance(b,str)
False
>>> isinstance(b,int)
True
下面的程序展示了isinstance函数的使用:
def 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(9999999999999999999999999L)
displayNumType(565.8)
displayNumType(-344.3+34.4j)
displayNumType('xxx')
代码运行结果如下:
-69 is a number of type: int
9999999999999999999999999 is a number of type: long
565.8 is a number of type: float
(-344.3+34.4j) is a number of type: complex
xxx is not a number at all!!!
6.len(object) -> integer
len()函数返回字符串和序列的长度。
>>> len("aa")
2
>>> len([1,2])
2
7.pow(x,y[,z])
pow()函数返回以x为底,y为指数的幂。如果给出z值,该函数就计算x的y次幂值被z取模的值。
- 上一篇:Python入门篇之文件
- 下一篇:python文件操作整理汇总