1.获取对象的信息
a.使用type()函数判断对象类型
>>> type(123) <class 'int'> >>> type('str') <class 'str'> >>> type(None) <type(None) 'NoneType'>
b.如果一个变量指向函数或者类,也可以用type()
判断
>>> type(abs) <class 'builtin_function_or_method'> >>> type(a) <class '__main__.Animal'>
c.使用type()判断两个对象的类型是否相同
>>> type(123)==type(456) True >>> type(123)==int True >>> type('abc')==type('123') True >>> type('abc')==str True >>> type('abc')==type(123) False
2.使用isinstance():判断一个对象是否是某种类型,还可以判断是否某些类型中的一种
>>> isinstance('a', str) True >>> isinstance(123, int) True >>> isinstance([1, 2, 3], (list, tuple)) True >>> isinstance((1, 2, 3), (list, tuple)) True
3.使用dir():如果要获得一个对象的所有属性和方法,可以使用dir()
函数,它返回一个包含字符串的list
>>> dir('ABC') ['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill'
4.使用getattr(), setattr(), hasattr()操作一个对象的状态
class MyObject(object): def __init__(self): self.x = 9 def power(self): return self.x * self.x obj = MyObject() print(hasattr(obj, 'x')) # 有属性'x'吗? print(hasattr(obj, 'y')) # 有属性'y'吗? setattr(obj, 'y', 19) # 设置一个属性'y' print(hasattr(obj, 'y')) # 设置一个属性'y' print(getattr(obj, 'y')) # 获取属性'y'