python isinstance()函数和type()函数

一、type()用法

描述:

  python的 type 函数有两个用法,当只有一个参数的时候,返回对象的类型。当有三个参数的时候返回一个类对象。

语法:

  一个参数:type(object)

  三个参数:type(name,bases,dict)

用法:

一个参数时,type()返回一个对象的数据类型

 1 >>> type(1)
 2 <class ‘int‘>
 3 >>> type(‘alex‘)
 4 <class ‘str‘>
 5 >>> type([1,2,3])
 6 <class ‘list‘>
 7 >>> type((1,2,3))
 8 <class ‘tuple‘>
 9 >>> type({‘zero‘:0,‘one‘:1})
10 <class ‘dict‘>
11 >>> type(1) == int
12 True
13 >>>

三个参数时:

name:类名

bases: 父类的元组

dict: 类的属性方法和值组成的键值对

创建一个类

 1 # 构造函数
 2 def __init__(self, name):
 3     self.name = name
 4 # 实例(普通)方法
 5 def instancetest(self):
 6     print(‘this is instance method‘)
 7
 8 # 类方法
 9 @classmethod
10 def classtest(cls):
11     print(‘This is a class method‘)
12
13 # 静态方法
14 @staticmethod
15 def statictest(n):
16     print(‘This is a static method %s‘ % n)
17
18 #创建类
19 test_property = {‘number‘: 1, ‘__init__‘:__init__,‘instancetest1‘:instancetest,
20                             ‘classtest‘: classtest, ‘statictest‘: statictest}# 属性和方法
21 Test = type(‘Tom‘, (object,), test_property)
22
23 # 实例化
24 test = Test(‘alex‘)
25 print(test.name)
26 print(test.number)
27 test.instancetest1()
28 test.classtest()
29 test.statictest(7)

执行结果:

1 alex
2 1
3 this is instance method
4 This is a class method
5 This is a static method 7

用help()打印Test的详细信息

class Tom(builtins.object)
 |  Tom(name)
 |
 |  Methods defined here:
 |
 |  __init__(self, name)
 |      # 构造函数
 |
 |  instancetest1 = instancetest(self)
 |      # 实例(普通)方法
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  classtest() from builtins.type
 |      # 类方法
 |
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |
 |  statictest(n)
 |      # 静态方法
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  number = 1

可以看出我们创建了一个Test类,包含一个实例方法包含一个构造方法__init__,实例方法statictest,类方法classtest,静态方法statictest1,和一个属性number =1。

注意:

Type和Object

type为对象的顶点,所有对象都创建自type。

object为类继承的顶点,所有类都继承自object。

python中万物皆对象,一个python对象可能拥有两个属性,__class__ 和 __base____class__ 表示这个对象是谁创建的,__base__ 表示一个类的父类是谁。

1 >>> object.__class__
2 <class ‘type‘>
3 >>> type.__base__
4 <class ‘object‘>

可以得出结论:

  • type类继承自object
  • object的对象创建自type

二、isinstance() 用法

描述:

判断一个对象时否来自一个已知类型

语法:

isinstance(object, classinfo)

参数:

  • object -- 实例对象。
  • classinfo -- 可以是直接或间接类名、基本类型或者由它们组成的元组。

返回值:

如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False。

1 >>>a = 2
2 >>> isinstance (a,int)
3 True
4 >>> isinstance (a,str)
5 False
6 >>> isinstance (a,(str,int,list))    # 是元组中的一个返回 True
7 True

三、type()和isintance()函数的区别

isinstance() 与 type() 区别:

  • type() 不会认为子类是一种父类类型,不考虑继承关系。
  • isinstance() 会认为子类是一种父类类型,考虑继承关系。

如果要判断两个类型是否相同推荐使用 isinstance()。

1 class A(object):
2     pass
3 class B(A):
4     pass
5
6 print(isinstance(A(), A))
7 print(isinstance(B(), A))
8 print(type(A()) == A)
9 print(type(B()) == A)

执行结果:

1 True
2 True
3 True
4 False

原文地址:https://www.cnblogs.com/weststar/p/11428312.html

时间: 2024-08-01 15:15:01

python isinstance()函数和type()函数的相关文章

《初识Python之认识常量type函数》

1.2 认识常量 1.常量:我们用的就是它字面意义上的值或内容. 2.数字(Number) (1)整数表示:97. (2)浮点数表示:5.29 或 78.2E-4(E 表示 10 的幂,78.2*10^-4). (3)布尔:True.False. 3.字符串(String):字符的序列. 字符串的声明 (1)单引号:’Iamastring’(字符串) (2)双引号:”Iamastring”(字符串) (3)三引号:’’’Iamastring’’’(多行注释,不是字符串) 注意:单引号.双引号.三

Pytthon:type函数和 isinstance 函数及区别

Python中,type和isinstance都可以进行类型检查,用的最多的就是type()了(其实我是一直用type()).内建函数type(object)用于返回当前对象的类型,比如type(1)返回<type 'int'>.因此可以通过与python自带模块types中所定义的名称进行比较,根据其返回值确定变量类型是否符合要求.例如判读一个变量a是不是list类型,可以使用以下代码: if type(a) is types.ListType: 所有的基本类型对应的名称都可以在types模

python isinstance函数(21)

1. 简介 isinstance() 函数是 python 中的一个内置函数,主要用于检测变量类型,返回值是bool值 ,在python内置函数中,与该函数相似的还有另外一个内置函数  type(). 2.语法 isinstance(object,classinfo) 参数: object : 实例对象. classinfo : 可以是直接或者间接类名.基本类型或者由它们组成的元组. 返回值:如果对象的类型与classinfo类型相同则返回 True,否则返回 False. a = 2 isin

python isinstance、isalnum函数用法

今天写一个校验的时候,遇到了三个函数,记下来以备用吧 isinstance.isalnum.len 相比大家都知道type()函数,判断一个对象的数据类型: In [1]: test = "abc123" In [2]: type(test) Out[2]: str In [3]: test = 123 In [4]: type(test) Out[4]: int 接下来介绍 isinstance数据类型,该函数用来判断是否为已知的数据类型,而type函数则是判断未知的数据类型,还是撸

Python内置函数(65)——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 统一动态创建多个model对应的modelForm类(type()函数)

一.ModelForm的用法 ModelForm对用户提交的数据有验证功能,但比Form要简单的多 from django.forms import ModelForm # 导入ModelFormclass customerModelForm(ModelForm):     class Meta:         model=models.UserInfo         fields="__all__"         labels={             'name':'用户名

python中3个帮助函数help、dir、type的使用

1.help函数:查看模块.函数.变量的详细说明: 查看模块 help("modules") 查看包  help("json") 查看类 help(json.JSONDecoder) 查看函数 help(json.dump) 2.dir函数:查看变量可用的函数或方法 >>> import time>>> dir(time)['__doc__', '__name__', '__package__', 'accept2dyear',

Python自动化运维之函数进阶

1.函数嵌套函数的嵌套定义:在一个函数的内部,又定义了另外一个函数函数的嵌套调用:在调用一个函数的过程中,又调用了其他函数代码: >>> def f1(): ...     def f2(): ...         print('from f2') ...         def f3(): ...             print('from f3') ...         f3() ...     f2() ... 执行结果: >>> f1() from f2

python学习之- 内置函数

内置方法:1:abs():取绝对值2:all():当可迭代对象里所有均为真时结果为真. all([1,2,3])3:any():当可迭代对象里任意一个数据为真结果即为真.any([0,1,2])4:ascii():打印一个对象以字符串的表现形式.[ascii([1,'你好'])] 使用率低.5:bin(x):把十进制整数转二进制.bin(1) / bin(255)以 0b开头.6:bool():真假判断7:bytearray():可修改的二进制字节格式. 很少用 b = bytearray('a