Python的type函数结果你知道嘛

目录
  • isinstance() 与 type() 区别:
  • type函数结果举例,主要有六大类:
  • 总结

简介:type() 函数可以对数据的类型进行判定。

isinstance() 与 type() 区别:

type() 不会认为子类是一种父类类型,不考虑继承关系。
isinstance() 会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()。

type函数结果举例,主要有六大类:

1、标准数据类型。

2、module模块类型:主要来源于模块安装并使用

3、type类型:主要来源于标准数据类型的类对象

4、程序员新增的类,自定义的类型:<class ‘main.XXX’>、NoneType

5、builtin_function_or_method 内置函数或者方法

6、其他拓展类型如:collections.Counter、collections.deque等

源码:

import time
import random
import asyncio
import collections
# 基本数据类型
print(type(1))  # <class 'int'>
print(type(3.14))  # <class 'float'>
print(type("hello"))  # <class 'str'>
print(type([1, 2]))  # <class 'list'>
print(type((1, "a")))  # <class 'tuple'>
print(type({"name": "tom"}))  # <class 'dict'>
print(type(False))  # <class 'bool'>
print("*" * 30)
# <class 'module'>
print(type(time))
print(type(random))
print(type(asyncio))
print("*" * 30)
# <class 'type'>
print(type(type))
print(type(int))
print(type(float))
print(type(bool))
print(type(str))
print(type(dict))
print(type(list))
print(type(tuple))
print(type(set))
print("*" * 30)

# 自定义的类型:<class '__main__.XXX'>
class A:
    x = 111
    def __init__(self):
        self.x = 1
    def run(self):
        pass
    @staticmethod
    def say():
        pass
    @classmethod
    def live(cls):
        pass
    @property
    def sleep(self):
        pass

a = A()
print(type(A))  # <class 'type'>
print(type(object))  # <class 'type'>
print(type(a))  # <class '__main__.A'>
# <class 'NoneType'>
print(type(a.__init__()))
print(type(a.run()))
print(type(a.say()))
print(type(a.live()))
print(type(a.sleep))
print(type(A.x))  # <class 'int'> 与初始值类型一致
print(type(a.x))  # <class 'int'> 与初始值类型一致
print("*" * 30)
# <class 'builtin_function_or_method'>
print(type(None))
print(type(bin))
print(type(len))
print(type(min))
print(type(dir))
print("*" * 30)
data = "message"
result = collections.Counter(data)
dict1 = collections.OrderedDict({"name": "Tom", "age": 25, "address": "CN"})
deq1 = collections.deque("abc")
print(type(result))  # <class 'collections.Counter'>
print(type(dict1))  # <class 'collections.OrderedDict'>
print(type(deq1))  # <class 'collections.deque'>

实际应用举例:

1、判定是否是lambda类型

2、判定是否是函数类型

3、判定是否是方法

4、判定生成器类型等

源码:

from types import LambdaType, MethodType, GeneratorType, FunctionType, BuiltinFunctionType
test1 = lambda x: x + 1
# 判定是否是lambda类型。需要注意的是lambda就是函数类型,本质是一样的
print(type(test1) == LambdaType)  # True
# 判定是否是函数类型
print(type(test1) == FunctionType)  # True
# 判定是否是内置函数类型
print(type(bin) == BuiltinFunctionType)  # True

class Test2:
    def run(self):
        pass

test2 = Test2()
# 判定是否是方法
print(type(test2.run) == MethodType)
# 判定生成器类型
a = (x * x for x in range(1, 10))
print(type(a) == GeneratorType)

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注我们的更多内容!

(0)

相关推荐

  • Python内置函数Type()函数一个有趣的用法

    今天在网上看到type的一段代码 ,然后查了一下文档,才知道type还有三个参数的用法. http://docs.python.org/2/library/functions.html#type 以前只是知道type可以检测对象类型.然后发现了一个有趣的用法. 复制代码 代码如下: def println(self): a = 1 + 1 print "%s,%s" % (self.aa, a) A = type('A',(),{'aa':'print a', 'println': p

  • Python基于内置函数type创建新类型

    英文文档: class type(object) class type(name, bases, dict) With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__. The isinstance() built-in function is recommended

  • Python astype(np.float)函数使用方法解析

    我的数据库如图 结构 我取了其中的name age nr,做成array,只要所取数据存在str型,那么取出的数据,全部转化为str型,也就是array阵列的元素全是str,不管数据库定义的是不是int型. 那么问题来了,取出的数据代入公式进行计算的时候,就会类型不符,这是就用到astype(np.float) 代码如下 import pymysql import numpy as np conn = pymysql.connect(host='39.106.168.84', user='xxx

  • 深入浅析Python获取对象信息的函数type()、isinstance()、dir()

    type()函数: 使用type()函数可以判断对象的类型,如果一个变量指向了函数或类,也可以用type判断. 如: class Student(object): name = 'Student' a = Student() print(type(123)) print(type('abc')) print(type(None)) print(type(abs)) print(type(a)) 运行截图如下: 可以看到返回的是对象的类型. 我们可以在if语句中判断比较两个变量的type类型是否相

  • Python中type的构造函数参数含义说明

    测试代码如下: 复制代码 代码如下: class ModelMetaClass(type):      def __new__(cls,name,base,attrs):          logging.info("cls is:"+str(cls))          logging.info("name is:"+str(name))          logging.info("base is:"+str(base))         

  • Python调用ctypes使用C函数printf的方法

    在Python程序中导入ctypes模块,载入动态链接库.动态链接库有三种:cdll以及windows下的windll和oledll,cdll载入导出函数使用标准的cdecl调用规范的库,而windll载入导出函数符合stdcall调用规范(Win32 API的原生约定)的库,oledll也使用stdcall调用规范,并假设函数返回Windows的HRESULT错误代码.错误代码用于在出错时自动抛出WindowsError这个Python异常,可以使用COM函数得到具体的错误信息. 使用cdll

  • Python的type函数结果你知道嘛

    目录 isinstance() 与 type() 区别: type函数结果举例,主要有六大类: 总结 简介:type() 函数可以对数据的类型进行判定. isinstance() 与 type() 区别: type() 不会认为子类是一种父类类型,不考虑继承关系. isinstance() 会认为子类是一种父类类型,考虑继承关系. 如果要判断两个类型是否相同推荐使用 isinstance(). type函数结果举例,主要有六大类: 1.标准数据类型. 2.module模块类型:主要来源于模块安装

  • 详解Python中的 type()函数

    目录 你好类型 type()和数字 序列类型 自定义数据类型 Python type() 函数摘要 将通过各种例子来了解如何在 Python 中使用 type() 函数. 你好类型 打印 "Hello World "几乎是你学习任何编程语言时做的第一件事.让我们用 type() 函数来检查一下. my_var = 'Hello World' print(type(my_var)) <class 'str'> 我们将在本文的所有例子中使用同一个 my_var变量用于本教程中的

  • Python之eval()函数危险性浅析

    一般来说Python的eval()函数可以把字符串"123"变成数字类型的123,但是PP3E上说它很危险,还可以执行其他命令! 对此进行一些试验.果然,如果python写的cgi程序中如果使用eval()而非int()来转换诸如年龄这样的输入框中的内容时是非常危险的.不仅可以看见列出系统的全部文件,还可以执行删除文件,察看文件源代码等危险操作! 试着写了个程序,想把本地的脚本文件同过这样的形式一行一行的写到服务器的某个文件里,可最后失败在无法输入换行符"/n",在

  • Python中enumerate函数代码解析

    enumerate函数用于遍历序列中的元素以及它们的下标. enumerate函数说明: 函数原型:enumerate(sequence, [start=0]) 功能:将可循环序列sequence以start开始分别列出序列数据和数据下标 即对一个可遍历的数据对象(如列表.元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标. 举例说明: 存在一个sequence,对其使用enumerate将会得到如下结果: start        sequence[0]

  • python开发之函数定义实例分析

    本文实例讲述了python开发之函数定义方法.分享给大家供大家参考,具体如下: 下面是我做的几个用列: #python中的函数定义,使用和传参 def_str = '''\ python中的函数以如下形式声明: def 函数名称([参数1,参数2,参数3......]): 执行语句 如: def helloWorld(): print('hello') if __name__ == '_main__': helloWorld() 输出:hello ''' print(def_str) #下面进行

  • Python入门及进阶笔记 Python 内置函数小结

    内置函数 常用函数 1.数学相关 •abs(x) abs()返回一个数字的绝对值.如果给出复数,返回值就是该复数的模. 复制代码 代码如下: >>>print abs(-100) 100 >>>print abs(1+2j) 2.2360679775 •divmod(x,y) divmod(x,y)函数完成除法运算,返回商和余数. 复制代码 代码如下: >>> divmod(10,3) (3, 1) >>> divmod(9,3) (

  • python中的函数用法入门教程

    本文较为详细的讲述了Python程序设计中函数的用法,对于Python程序设计的学习有不错的借鉴价值.具体分析如下: 一.函数的定义: Python中使用def关键字定义函数,函数包括函数名称和参数,不需要定义返回类型,Python能返回任何类型: #没有返回值的函数,其实返回的是None def run(name): print name,'runing' #函数体语句从下一行开始,并且第一行必须是缩进的 >>>run('xiaoming') xiaoming runing >&

  • Python内置函数—vars的具体使用方法

    本文文章主要介绍了Python内置函数-vars的具体使用方法,分享给大家,具体如下: 英文文档: vars([object]) Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.Objects such as modules and instances have an updateable __dict__ attribute; h

  • 基于python内置函数与匿名函数详解

    内置函数 Built-in Functions abs() dict() help() min() setattr() all() dir() hex() next() slice() any() divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod() bin() eval() int() open() str() bool() exec() isinstance() pow() super

  • Python常见工厂函数用法示例

    本文实例讲述了Python常见工厂函数用法.分享给大家供大家参考,具体如下: 工厂函数:能够产生类实例的内建函数. 工厂函数是指这些内建函数都是类对象, 当调用它们时,实际上是创建了一个类实例. python中的工厂函数举例如下: 1>int(),long(),float(),complex(),bool() >>> a=int(9.9) >>> a 9 >>> b=long(45) >>> b 45L >>>

随机推荐