脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 详解Python中的type和object

详解Python中的type和object

2021-03-27 00:55Harvard_Fly Python

这篇文章主要介绍了Python中type和object的相关知识,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下

type  所有类是type生成的

?
1
2
3
4
5
6
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:

?
1
2
3
4
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

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

result:

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

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

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

result:

?
1
2
3
type 的基类是:(<class 'object'>,)
type object:<class 'type'>
object 的基类是:()

详解Python中的type和object

总结

以上所述是小编给大家介绍的Python中type和object,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://www.cnblogs.com/FG123/p/9463707.html

延伸 · 阅读

精彩推荐