判断对象类型 type()

本文介绍了如何在Python中使用type()函数来判断变量的数据类型,并展示了如何利用types模块简化类型比较的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本类型都可以用type()判断:

>>> type(123)
<type 'int'>
>>> type('str')
<type 'str'>
>>> type(None)
<type 'NoneType'>

如果一个变量指向函数或者类,也可以用type()判断:

>>> type(abs)
<type 'builtin_function_or_method'>
>>> type(a)
<class '__main__.Animal'>

但是type()函数返回的是什么类型呢?它返回type类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同:

>>> type(123)==type(456)
True
>>> type('abc')==type('123')
True
>>> type('abc')==type(123)
False

但是这种写法太麻烦,Python把每种type类型都定义好了常量,放在types模块里,使用之前,需要先导入:

>>> import types
>>> type('abc')==types.StringType
True
>>> type(u'abc')==types.UnicodeType
True
>>> type([])==types.ListType
True
>>> type(str)==types.TypeType
True

最后注意到有一种类型就叫TypeType,所有类型本身的类型就是TypeType,比如:

>>> type(int)==type(str)==types.TypeType True

转载于:https://www.cnblogs.com/pythonabc/p/6741916.html

TypeScript中,可以使用类型断言和类型保护来判断对象类型。 1. 类型断言(Type Assertion): 类型断言是一种告诉编译器某个值的具体类型的方式。可以使用尖括号语法或者as关键字进行类型断言。 例如: ```typescript let obj: any = "hello"; let strLength: number = (<string>obj).length; // 使用尖括号语法进行类型断言 let strLength: number = (obj as string).length; // 使用as关键字进行类型断言 ``` 2. 类型保护(Type Guard): 类型保护是一种在特定范围内缩小变量的类型的方式,以便在该范围内使用特定类型的属性和方法。 TypeScript提供了多种类型保护的方式,包括typeof类型保护、instanceof类型保护和自定义类型保护。 - typeof类型保护: 可以使用typeof操作符来判断基本类型的变量类型。 例如: ```typescript function printLength(obj: string | number) { if (typeof obj === "string") { console.log(obj.length); // 在这个范围内,obj被缩小为string类型 } else { console.log(obj); // 在这个范围内,obj被缩小为number类型 } } ``` - instanceof类型保护: 可以使用instanceof操作符来判断对象的具体类型。 例如: ```typescript class Animal { name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { breed: string; constructor(name: string, breed: string) { super(name); this.breed = breed; } } function printName(animal: Animal) { if (animal instanceof Dog) { console.log(animal.breed); // 在这个范围内,animal被缩小为Dog类型 } else { console.log(animal.name); // 在这个范围内,animal被缩小为Animal类型 } } ``` - 自定义类型保护: 可以使用自定义的类型保护函数来判断对象的具体类型。 例如: ```typescript function isString(obj: any): obj is string { return typeof obj === "string"; } function printLength(obj: string | number) { if (isString(obj)) { console.log(obj.length); // 在这个范围内,obj被缩小为string类型 } else { console.log(obj); // 在这个范围内,obj被缩小为number类型 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值