Python对象信息获取函数详解:type()、isinstance()、dir()

1 下载量 192 浏览量 更新于2024-08-30 收藏 124KB PDF 举报
Python 获取对象信息的函数 type()、isinstance()、dir() Python 中有多种方式可以获取对象的信息,其中包括 type()、isinstance() 和 dir() 函数,这三个函数分别可以判断对象的类型、判断对象是否是某个类的实例、获取对象的所有属性和方法。 type() 函数 type() 函数可以判断对象的类型,如果一个变量指向了函数或类,也可以用 type() 判断。例如: ``` class Student(object): name = 'Student' a = Student() print(type(123)) # 输出:<class 'int'> print(type('abc')) # 输出:<class 'str'> print(type(None)) # 输出:<class 'NoneType'> print(type(abs)) # 输出:<class 'builtin_function_or_method'> print(type(a)) # 输出:<class '__main__.Student'> ``` 可以看到,type() 函数返回的是对象的类型。我们可以在 if 语句中判断比较两个变量的 type 类型是否相同。例如: ``` class Student(object): name = 'Student' a = Student() if type(123) == type(456): print("True") # 输出:True ``` types 模块 如果要判断一个对象是否是函数怎么办?我们可以使用 types 模块中定义的常量。types 模块中提供了四个常量:types.FunctionType、types.BuiltinFunctionType、types.LambdaType、types.GeneratorType,分别代表函数、内建函数、匿名函数、生成器类型。例如: ``` import types def fn(): pass print(type(fn) == types.FunctionType) # 输出:True print(type(abs) == types.BuiltinFunctionType) # 输出:True print(type(lambda x: x) == types.LambdaType) # 输出:True print(type((x for x in range(10))) == types.GeneratorType) # 输出:True ``` isinstance() 函数 对于有继承关系的类,我们要判断该类的类型,可以使用 isinstance() 函数。例如: ``` class Animal(object): def run(self): print("动物在跑") class Dog(Animal): def eat(self): print("狗在吃") class Cat(Animal): def run(self): print("猫在跑") dog1 = Dog() cat1 = Cat() print(isinstance(dog1, Dog)) # 输出:True print(isinstance(dog1, Animal)) # 输出:True print(isinstance(cat1, Cat)) # 输出:True print(isinstance(cat1, Animal)) # 输出:True ``` 可以看到,isinstance() 函数可以判断对象是否是某个类的实例。 dir() 函数 dir() 函数可以获取对象的所有属性和方法。例如: ``` class Student(object): name = 'Student' a = Student() print(dir(a)) # 输出:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name'] ``` 可以看到,dir() 函数返回的是对象的所有属性和方法。 type()、isinstance() 和 dir() 函数可以帮助我们获取对象的信息,从而更好地理解和使用 Python 对象。