Python对象信息获取函数详解:type()、isinstance()、dir()
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 对象。
2023-03-17 上传
2022-10-30 上传
511 浏览量
710 浏览量
147 浏览量
点击了解资源详情
点击了解资源详情
235 浏览量
175 浏览量
![](https://profile-avatar.csdnimg.cn/default.jpg!1)
weixin_38670391
- 粉丝: 7
最新资源
- 设计模式:面向对象软件的复用基础与实例解析
- 开发指南:Microsoft Office 2007与Windows SharePoint Services
- DB2 Version 9 Command Reference for Linux, UNIX, Windows
- EJB技术详解:Java与J2EE架构中的企业级组件
- Spring整合JDO与Hibernate:Kodo的使用教程
- PS/2鼠标接口详解:物理连接与协议介绍
- SQL触发器全解析:经典语法与应用场景
- 在线优化Apache Web服务器响应时间
- Delphi函数全解析:AnsiResemblesText, AnsiContainsText等
- 基于SoC架构的Network on Chip技术简介
- MyEclipse 6 Java开发完全指南
- VBA编程基础:关键指令与工作簿工作表操作
- Oracle学习与DBA守则:通往成功的道路
- Windows Server 2003 DNS配置教程
- 整合JSF, Spring与Hibernate:构建实战Web应用
- 在Eclipse中使用HibernateSynchronizer插件提升开发效率