1.type()
type(object),接收一个对象作为参数,并返回它的类型。它的返回值是一个类型对象。
2.com()
Python2中,com(obj1,obj2),用于比较两个对象obj1和obj2,如果obj1小于obj2,则返回一个负整数,如果obj1大于obj2,则返回一个正整数,如果obj1等于obj2,则返回0。
Python3中,使用operator模块来实现同样的功能,要使用operator模块需要先导入该模块。
operator模块的功能如下:
函数 | 含义 |
operator.lt(a,b) | a<b |
operator.le(a,b) | a<=b |
operator.eq(a,b) | a==b |
operator.ne(a,b) | a!=b |
operator.gt(a,b) | a>b |
operator.ge(a,b) | a>=b |
import operator
a,b = -4,12
print(operator.lt(a,b))
print(operator.le(a,b))
print(operator.eq(a,b))
print(operator.ne(a,b))
print(operator.gt(a,b))
print(operator.ge(a,b))
结果:
True
True
False
True
False
False
3.str()和repr()
内建函数str()和repr()可以方便的以字符串的方式获取对象的内容、类型、数值属性等信息。
str()函数得到的字符串可读性好
repr()函数得到的字符串通常可以用来重新获得该对象
print(str(4.53-2j))
print(str(1))
print(str(2e10))
print(str([0,5,9,9]))
print()
print(repr([0,5,9,9]))
# print(`[1,1,1]`)
结果:
(4.53-2j)
1
20000000000.0
[0, 5, 9, 9]
[0, 5, 9, 9]
4.isinstance()
确认对象的类型
def displayNumType(num):
print(num,"is",end=" ")
if isinstance(num,(int,float,complex)):
print("a number of type:",type(num))
else:
print("not a number at all!!")
displayNumType(-69)
displayNumType(98.6)
displayNumType(-5.2+1.9j)
displayNumType("xxx")
结果:
-69 is a number of type: <class 'int'>
98.6 is a number of type: <class 'float'>
(-5.2+1.9j) is a number of type: <class 'complex'>
xxx is not a number at all!!
例子进阶:
def displayNumType(num):
print(num,"is",end=" ")
if type(num) == type(0):
print("an integer")
elif type(num) == type(0.0):
print("a float")
elif type(num) == type(0 + 0j):
print("a complex")
else:
print("not a number at all!!")
displayNumType(-69)
displayNumType(98.6)
displayNumType(-5.2+1.9j)
displayNumType("xxx")
结果:
-69 is an integer
98.6 is a float
(-5.2+1.9j) is a complex
xxx is not a number at all!!