详解Python中的type和object

yipeiwu_com5年前Python基础

type  所有类是type生成的

a = 1
b = "abc"
print("type a:{}".format(type(a)))
print("type int:{}".format(type(int)))
print("type b:{}".format(type(b)))
print("type str:{}".format(type(str)))

result:

type a:<class 'int'>
type int:<class 'type'>
type b:<class 'str'>
type str:<class 'type'>

在python中是一切皆对象的,类其实也是对象,首先type生成了<class 'int'>这个对象,<class 'int'>又生成了1这个对象,type --> int --> 1

同样,type生成了<class 'str'>这个对象,<class 'type'>又生成了"abc"这个对象,type --> str--> “abc”,即type -->生成类对象 -->对象

object   所有类的最顶层基类是object

print("int 的基类是:{}".format(int.__bases__))
print("str 的基类是:{}".format(str.__bases__))

result:

int 的基类是:(<class 'object'>,)
str 的基类是:(<class 'object'>,)
<class 'int'>和<class 'str'>的基类都是 <class 'object'> 即:object是最顶层的基类

type与object的关系(type的基类是object,object是type生成的,object的基类为空)

print("type 的基类是:{}".format(type.__bases__))
print("type object:{}".format(type(object)))
print("object 的基类是:{}".format(object.__bases__))

result:

type 的基类是:(<class 'object'>,)
type object:<class 'type'>
object 的基类是:()

 

总结

以上所述是小编给大家介绍的Python中type和object,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Flask之flask-session的具体使用

flask-session是flask框架的session组件,由于原来flask内置session使用签名cookie保存,该组件则将支持session保存到多个地方,如: re...

Python IDLE 错误:IDLE''s subprocess didn''t make connection 的解决方案

Python IDLE 错误描述: Subprocess Startup Error IDLE's subprocess didn't make connection. Eithe...

Django中信号signals的简单使用方法

正文 在平时的开发过程中,我们会遇到一些特殊的应用场景,如果你想要在执行某种操作之前或者之后你能够得到通知,并对其进行一些你想要的操作时,你就可以用Django中的信号(signals)...

对python3新增的byte类型详解

对python3新增的byte类型详解

在python2中字节类型同字符类型区分不大,但是在python3中最重要的特性是对文本和二进制数据做了更加清晰的区分,文本总是Unicode,由字符类型表示,而二进制数据则由byte类...

Python魔法方法详解

据说,Python 的对象天生拥有一些神奇的方法,它们总被双下划线所包围,他们是面向对象的 Python 的一切。 他们是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了这些方...