一、type()用法

描述:

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

语法:

  一个参数:type(object)

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

用法:

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

 >>> type(1)
<class 'int'>
>>> type('alex')
<class 'str'>
>>> type([1,2,3])
<class 'list'>
>>> type((1,2,3))
<class 'tuple'>
>>> type({'zero':0,'one':1})
<class 'dict'>
>>> type(1) == int
True
>>>

三个参数时:

name:类名

bases: 父类的元组

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

创建一个类

 # 构造函数
def __init__(self, name):
self.name = name
# 实例(普通)方法
def instancetest(self):
print('this is instance method') # 类方法
@classmethod
def classtest(cls):
print('This is a class method') # 静态方法
@staticmethod
def statictest(n):
print('This is a static method %s' % n) #创建类
test_property = {'number': 1, '__init__':__init__,'instancetest1':instancetest,
'classtest': classtest, 'statictest': statictest}# 属性和方法
Test = type('Tom', (object,), test_property) # 实例化
test = Test('alex')
print(test.name)
print(test.number)
test.instancetest1()
test.classtest()
test.statictest(7)

执行结果:

 alex
1
this is instance method
This is a class method
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__ 表示一个类的父类是谁。

 >>> object.__class__
<class 'type'>
>>> type.__base__
<class 'object'>

可以得出结论:

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

二、isinstance() 用法

描述:

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

语法:

isinstance(object, classinfo)

参数:

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

返回值:

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

 >>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list)) # 是元组中的一个返回 True
True

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

isinstance() 与 type() 区别:

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

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

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

 class A(object):
pass
class B(A):
pass print(isinstance(A(), A))
print(isinstance(B(), A))
print(type(A()) == A)
print(type(B()) == A)

执行结果:

 True
True
True
False

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

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

    <初识Python之认识常量type函数> 1.2 认识常量 1.常量:我们用的就是它字面意义上的值或内容. 2.数字(Number) (1)整数表示:97. (2)浮点数表示:5.29 ...

  2. python中一些有用的函数------持续更新中

    strip() 函数 用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列. str2 = " Runoob " # 去除首尾空格 print (str2.strip()) ...

  3. 【我要学python】MethodType和isinstance和Type函数

    一.首先来看isinstance: a=6 isinstance(a,int) #返回Ture isinstance(a,str) #返回False isinstance (a,(str,int,li ...

  4. python---issubclass/type/isinstance/ 反射(内置函数getattr/delattr...)

    # 一 python面向对象-内置函数(issubclass(), type(), isinstance()) # issubclass 判断xxxx类是否是xxxx类的子类 class egg: p ...

  5. python入门(二):isinstance、内置函数、常用运算等

    1.    isinstance(变量名,类型)                           #判断什么类型 ps: 只支持输入两个参数,输入3个参数会报错 >>> isin ...

  6. Python内置函数(43)——type

    英文文档: class type(object) class type(name, bases, dict) With one argument, return the type of an obje ...

  7. Python内置函数(65)——type

    英文文档: class type(object) class type(name, bases, dict) With one argument, return the type of an obje ...

  8. python之type函数

    python 的type 函数 的介绍的   下面就是此函数的参数   三个参数的意义 '''type(class_name, base_class_tuple, attribute_dict)cla ...

  9. Python type() 函数

    描述 type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象.类似isinstance() isinstance() 与 type() 区别: type() 不会认为子类是一 ...

随机推荐

  1. C# 一个网站

    http://www.aizhengli.com/aspnet-mvc5/6/aspnet-mvc5-member-user-register.html

  2. Maven入门指南10:Maven的生命周期和插件

    一个完整的项目构建过程通常包括清理.编译.测试.打包.集成测试.验证.部署等步骤,Maven从中抽取了一套完善的.易扩展的生命周期.Maven的生命周期是抽象的,其中的具体任务都交由插件来完成.Mav ...

  3. vue iview分页

    距离上次博客更新已经快一个月了,期间也有想法在空闲的时候更新几篇博文. 燃鹅,最近懒癌作祟,丢掉的东西越来越多,再不遏止的话就真成癌了. 趁着刚看完一篇心灵鸡汤,让打满鸡血的我总结下前段时间用到的iv ...

  4. 20180209-json&pickle&shelve模块

    什么是序列化? 序列化就是把内存里的数据类型转成字符串,以使其能够存储到硬盘中或在网络中传输到远程,因为硬盘和网络传输时只接收bytes 用于序列化的两个模块 1. json,用于字符串和python ...

  5. This program cannot be run in DOS mode.

    问题:通过ftp上传的exe执行时提示“This program cannot be run in DOS mode.” 解决方法:检查ftp传输模式,设置成binary模式上传即可 参考:https ...

  6. 微信小程序(1)--新建项目

    这些天看了一下最近特别火的微信小程序,发现和vue大同小异. 新建项目 为方便初学者了解微信小程序的基本代码结构,在创建过程中,如果选择的本地文件夹是个空文件夹,开发者工具会提示,是否需要创建一个 q ...

  7. svnkit 异常:Exception in thread "main" org.tmatesoft.svn.core.SVNException: svn: E200030: SQLite error

    https://stackoverflow.com/questions/16063105/org-tmatesoft-sqljet-core-sqljetexception-busy-error-co ...

  8. boost number handling

    Boost.Integer defines specialized for integers. 1. types for integers with number of bits #include & ...

  9. 深度学习中的batch、epoch、iteration的含义

    深度学习的优化算法,说白了就是梯度下降.每次的参数更新有两种方式. 第一种,遍历全部数据集算一次损失函数,然后算函数对各个参数的梯度,更新梯度.这种方法每更新一次参数都要把数据集里的所有样本都看一遍, ...

  10. mock.js模拟生成假数据

    mock使用方法很简单, 下面是简单的用法, 详细的用法可以看官方文档, 写的很清楚, 下面的代码直接拷贝到本地html文件, 双击打开即可生成你想要的数据 <!DOCTYPE html> ...