一、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. MySQL查询时报错Illegal mix of collations

    开发十年,就只剩下这套架构体系了! >>>   1.具体场景 两张表分别为: CREATE TABLE `tb_user` ( `id` bigint(20) NOT NULL AU ...

  2. k3 cloud查看附件提示授予目录NetWorkService读写权限

    打开文件的时候出现下面的提示: 解决办法: 解决办法:找到C:\Program Files(x86)\Kingdee\K3Cloud\WebSite\FileUpLoadServices,在下面创建F ...

  3. 常见前端面试题JS部分

    1.闭包 2.JS操作和获取cookie //创建cookie function setCookie(name, value, expires, path, domain, secure) { var ...

  4. ELKStack之操作深入(中)

    ELKStack之操作深入(中) 链接:https://pan.baidu.com/s/1V2aYpB86ZzxL21Hf-AF1rA 提取码:7izv 复制这段内容后打开百度网盘手机App,操作更方 ...

  5. python正则表达式 re (二)sub

    背景: re.sub是re模块重要的组成部分,并且功能也非常强大,主要功能实现正则的替换. re.sub定义: sub(pattern, repl, string, count=0, flags=0) ...

  6. 八、请求post、get、jsonp

    1.创建个 news 组件使用 2.在module.ts 引入模块 3.在使用的“Component”中不一样.这里是 http和jsonp 4.编写get请求查看效果 (1).编写好的get请求,点 ...

  7. mysql中文乱码解决办法

    Windows 在C:\Program Files\MySQL\MySQL Server 5.5\bin目录下 MySQLInstanceConfig.exe执行 重新配置character_set_ ...

  8. 为什么要用unittest

    '''为什么要使用单元测试框架?: 1.当用例很多的时候用来组织用例和执行用例 2.提供丰富的比较方法 3.提供丰富的日志''' import unittest import HTMLTestRunn ...

  9. BZOJ1899 [Zjoi2004]Lunch 午餐 贪心+DP

    题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=1899 题解 如果只有一个窗口,那么可以这样考虑:因为最后一个人打完饭的时间是固定的,那么不如就 ...

  10. SpringIntegration---Redis

    1.依赖 <dependency> <groupId>org.springframework.integration</groupId> <artifactI ...