一、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. Ajax ——数据解析

             Ajax应用中数据解析是非常重要的一件事情.一般服务器返回数据有三种格式:txt , xml,  json 1.解析txt       当服务器返回的数据为字符串,则这种Ajax数据 ...

  2. JavaScript给动态插入的元素添加事件绑定

    由于实际的需要,有时需要往网页中动态的插入HTML内容,并在插入的节点中绑定事件处理函数.我们知道,用Javascript向HTML文档中 插入内容,有两种方法, 一种是在写HTML代码写入JS,然后 ...

  3. H5中图片按照比例收缩,放大

    需求:后台传过来的图片不能够压缩,即使部分被截取也可以 传统方案:设置img元素如下: width: auto; height: auto; max-width: 100%; max-height: ...

  4. OC学习--继承

     1.什么是继承? 继承是指一个对象直接使用另一对象的属性和方法. 继承可以使得子类具有父类的各种属性和方法,而不是再次编写相同的代码.在子类继承父类的同时,可以重新定义某些属性,并重写某些方法, 即 ...

  5. 【记录】使用Navicat将表设计导出数据库设计文档

    INFORMATION_SCHEMA. Tables -- 表信息 INFORMATION_SCHEMA. COLUMNS -- 列信息 参考文章地址:https://blog.csdn.net/cx ...

  6. Error- Overloaded method value createDirectStream in error Spark Streaming打包报错

    直接上代码 StreamingExamples.setStreamingLogLevels() val Array(brokers, topics) = args // Create context ...

  7. docker:python与docker

    一:环境准备 pycharm:专业版(windows) docker ce 免费版(ubantu16.04) os: os:防火墙 二:开发流程 pycharm中开发环境搭建的工作原理: 1. pyc ...

  8. js实现动态加载input 提示信息

    思路:使用<datalist> 标签定义选项列表.请与 input 元素配合使用该元素,来定义 input 可能的值.datalist 及其选项不会被显示出来,它仅仅是合法的输入值列表.请 ...

  9. 【leetcode】1021. Best Sightseeing Pair

    题目如下: Given an array A of positive integers, A[i]represents the value of the i-th sightseeing spot, ...

  10. temp = yield i 这句话的意思?

    def test(): i = 0 while i < 5: temp = yield i # print(temp) i+=1 t = test() print(t.__next__()) p ...