python中type的含义和使用方法

发布时间:2020-05-22 16:36:19 作者:鸽子
来源:亿速云 阅读:1210

1. 简介

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 a  methond")

 

 

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()。


推荐阅读:
  1. python中list与tuple的含义和使用
  2. python中type和object有什么用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python type函数

上一篇:如何迁移域控角色?

下一篇:linux中连接MySQL的密码忘记了解决办法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》