python type函数

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深拷贝和浅拷贝

2.python is和==区别

3.python 自定义时间格式time

4.python递归函数

 

转载请注明猿说Python » python type函数

 


猜你喜欢

转载自blog.51cto.com/14531342/2476855