加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python中的一切皆对象

发布时间:2020-12-20 12:52:02 所属栏目:Python 来源:网络整理
导读:python中一切皆对象是这个语言灵活的根本。 函数和类也是对象,属于python的一等公民。 包括代码包和模块也都是对象。 python的面向对象更加彻底。 可以赋值给一个变量 可以添加到集合对象中 可以作为参数传递给函数 可以当作函数的返回值 在python中什么不

python中一切皆对象是这个语言灵活的根本。
函数和类也是对象,属于python的一等公民。
包括代码包和模块也都是对象。
python的面向对象更加彻底。

可以赋值给一个变量
可以添加到集合对象中
可以作为参数传递给函数
可以当作函数的返回值

在python中什么不是对象?
字符串是类str的对象
数字是类int的对象
元组是类tuple的对象
列表是类list的对象
字典是类dict的对象
函数是类function的对象
类是type的对象

将一个函数当作返回值的时候就是闭包,也就是装饰器的实现原理。

在python中,基础的数据类型(list,tuple,dict等)都是使用c++编写的,所以性能会非常高。

一、type/object/class

1.type和class

>>> a = 1
>>> type(a)
<class int>
>>> type(int)
<class type>

>>> b = "123"
>>> type(b)
<class str>
>>> type(str)
<class type>

>>> c = [1,2,3]
>>> type(c)
<class list>
>>> type(list)
<class type>

>>> d = (1,3)
>>> type(d)
<class tuple>
>>> type(tuple)

<class type>
>>> d = {"name":"kebi","age":18}
>>> type(d)
<class dict>
>>> type(dict)
<class type>

在python中基础数据类型有:字符串、数字、元组、列表、字典、集合等
它们分别由类str、int、tuple、list、dist、set实例出来的对象。
而类str、int、tuple、list、dist、set本身也是对象,它们都是由type这个创造创造出来的。

对于函数来说:
函数都是由类function创造出来的。

>>> def func():
... pass
...
>>> type(func)
<class function>
>>> type(func())
<class NoneType>
>>> type(function)
Traceback (most recent call last):
File "<stdin>",line 1,in <module>
NameError: name function is not defined

问题:
function这个类是怎么来的了?如果function是一个对象,那么为什么不能使用type打印类型。
原因也许是function超出了type的范围,因为它不是type创造的。类似的还有NoneType


对于类来说:
类都是由type创造出来

>>> class Person:
... pass
...
>>> type(Person)
<class type>
>>> type(Person()) #对象由类创建
<class __main__.Person>

既然type创造了如此多的类,那么type是怎么来的?

>>> type(type)
<class type> #自己创造自己

在python中,type有两个功能:
  a.打印对象的类型
 ? ? b.创造类

虽然上述代码并没有解释清楚一切对象的来源,但是很多的说明了type和class的关系——“type就是用来创造类的”

2.object

>>> print(int.__bases__)
(<class object>,)
>>> print(str.__bases__)
(<class object>,)

>>> print(Person.__bases__) #默认继承object
(<class object>,)
>>> class AnluPerson(Person):
... pass
...
>>> print(AnluPerson.__bases__)
(<class __main__.Person>,)
object是最顶层的基类。

>>> print(type.__bases__) #type的父类是object
(<class object>,)
>>> type(object) #object又是由type创造出来的
<class type>
>>> print(object.__bases__)
()
>>> type(type) #type自己创造自己
<class type>

?

关于type、object、class之间的关系示意图:

在python中,基础数据类型的类都是type的实例,type自生也是type的实例。
基础数据类型的类都是继承object。
对于function等先不管,我们可以说一切皆对象,一切都是type的对象,object是所有类的基类。

?

二、python中常见的数据类型

1.None 全局只有一个2.数值? int? float? complex? bool3.迭代类型4.序列类型? list? bytes、bytearray、memoryview(二进制序列)? range? tuple? str? array5.映射(dict)6.集合类型 dict与set实现原理相似,性能很高? set? frozenset7.上下文管理类型(with)8.其它? 模块类型? class和实例? 函数类型? 方法类型? 代码类型? object类型? type类型? ellipsis类型(省略号)? notimplemented类型

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读