描述

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

语法

type(object)

type(name, bases, dict)

用法

一个参数

type(object)

返回一个对象的类型,如:

In [1]: a = 10 

In [2]: type(a)
Out[2]: int

三个参数

tpye(name, bases, dict)

  • name 类名
  • bases 父类的元组
  • dict 类的属性方法和值组成的键值对

返回一个类对象:

# 实例方法
def instancetest(self):
print("this is a instance method") # 类方法
@classmethod
def classtest(cls):
print("this is a class method") # 静态方法
@staticmethod
def statictest():
print("this is a static method") # 创建类
test_property = {"name": "tom", "instancetest": instancetest, "classtest": classtest, "statictest": statictest}
Test = type("Test", (), test_property) # 创建对象
test = Test()
# 调用方法
print(test.name)
test.instancetest()
test.classtest()
test.statictest()

运行结果:

tom
this is a instance method
this is a class method
this is a static method

使用help打印Test的详细信息:

class Test(builtins.object)
| Methods defined here:
|
| instancetest(self)
| # 实例方法
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| classtest() from builtins.type
| # 类方法
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| statictest()
| # 静态方法
|
| ----------------------------------------------------------------------
| 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:
|
| name = 'tom'

可以看出我们创建了一个Test类,包含一个实例方法statictest,类方法classtest,静态方法statictest,和一个属性name = 'tom'。

type和isinstance

type不会认为子类是父类的类型,不会考虑继承关系。isinstance会任务子类是父类的类型,考虑继承关系。

Type和Object

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

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

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

In [1]: object.__class__
Out[1]: type In [2]: type.__base__
Out[2]: object

可以得出结论:

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

最新文章

  1. maven+springmvc+dubbo+zookeeper
  2. SQL Server 常用函数介绍
  3. ASP.NET 5中的那些K
  4. Flume配置
  5. python字符集选择
  6. JIRA官方:JIRA源代码集成
  7. Android 纯代码加入点击效果
  8. post提交数据长度限制问题
  9. 最全 Linux 磁盘管理基础知识全汇总
  10. 强大的IDEA开发工具
  11. python多进程并发和多线程并发和协程
  12. String字符串的常用方法
  13. IIS 部署问题 404
  14. IkAnalyzer2012FF_u1.jar免费下载
  15. Visual Studio 2015 将json转换为实体类
  16. 课程四(Convolutional Neural Networks),第一周(Foundations of Convolutional Neural Networks) —— 1.Practice questions:The basics of ConvNets
  17. C#语言————拼接、插入、替换、删除四种方法
  18. mac python3安装virtualenv出现的问题
  19. Spring Boot实战系列-----------邮件发送
  20. Mac下brew/memcached/nginx/iterm/zsh的安装

热门文章

  1. JavaWeb学习总结——文件上传和下载
  2. (4.1)mysql备份还原——mysql常见故障
  3. redis缓存和mysql数据库同步
  4. ansible的安装及基本使用
  5. host文件
  6. 各版本系统安装tesseract-ocr
  7. 报错解决——uwsgi错误invalid request block size
  8. Windows 7中200M神秘隐藏分区
  9. 20165236 第六周Java学习总结
  10. python基础入门--input标签、变量、数字类型、列表、字符串、字典、索引值、bool值、占位符格式输出