python中type的含义和使用方法
type() 函数是python中的一个内置函数,主要用于获取变量类型,在python内置函数中,与该函数相似的还有另外一个内置函数isinstance函数。
2.语法1
type(object)
参数:
object : 实例对象。
返回值:直接或者间接类名、基本类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
b = 12.12
c = "hello"
d = [1, 2, 3, "rr"]
e = {"aa": 1, "bb": "cc"}
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print("***"*20)
class Person(object):
def __init__(self, name):
self.name = name
def p(self):
print("this is amethond")
print(Person)
tom = Person("tom")
print("tom实例的类型是:%s" % type(tom))# 实例tom是Person类的对象。
输出结果:
1
2
3
4
5
6
7
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
************************************************************
<class '__main__.Person'>
tom实例的类型是:<class '__main__.Person'>
3.isinstance()与type()的区别isinstance() 会认为子类是一种父类类型,考虑继承关系。
type() 不会认为子类是一种父类类型,不考虑继承关系。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:何以解忧
@Blog(个人博客地址): shuopython.com
@WeChat Official Account(微信公众号):猿说python
@Github:www.github.com
@File:python_type.py
@Time:2019/11/22 21:25
@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!
"""
class People:
pass
class body(People):
pass
print(isinstance(People(), People))# returns True
print(type(People()) == People)# returns True
print(isinstance(body(), People))# returns True
print(type(body()) == People)# returns False
输出结果:
1
2
3
4
True
True
True
False
代码分析:
创建一个People对象,再创建一个继承People对象的body对象,使用 isinstance() 和 type() 来比较 People() 和 People时,由于它们的类型都是一样的,所以都返回了 True。
而body对象继承于People对象,在使用isinstance()函数来比较 body() 和 People时,由于考虑了继承关系,所以返回了 True,使用 type() 函数来比较 body() 和 People时,不会考虑 body() 继承自哪里,所以返回了 False。
如果要判断两个类型是否相同,则推荐使用isinstance()。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。