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,2,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
• bool

3.迭代類型

4.序列類型
• list
• bytes、bytearray、memoryview(二進制序列)
• range
• tuple
• str
• array

5.映射(dict)

6.集合類型 dict與set實現原理相似,性能很高
• set
• frozenset

7.上下文管理類型(with)

8.其它
• 模塊類型
• class和實例
• 函數類型
• 方法類型
• 代碼類型
• object類型
• type類型
• ellipsis類型(省略號)
• notimplemented類型


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM