您好,登錄后才能下訂單哦!
為什么Python中一切皆對(duì)象?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
引言
Java語言也是面向?qū)ο蟮恼Z言,但是Python要更加徹底
Python的面向?qū)ο筇匦裕撬褂闷饋盱`活的根本所在
對(duì)象的特點(diǎn)
可以賦值給一個(gè)變量
# 函數(shù)也是對(duì)象 def test(name): print(name) my_func = test # 注意 只寫函數(shù)名 和 函數(shù)名加括號(hào) 的區(qū)別 my_func("MetaTian") # 打?。篗etaTian
可以添加到集合中去
def plus(a, b): print(a+b) def minus(a, b): print(a-b) fun_list = [] fun_list.append(plus) fun_list.append(minus) for item in fun_list: item(2, 1) # result: # 3 # 1
可以作為參數(shù)傳遞給函數(shù)
def plus(a, b): print(a+b) def calculate(method, a, b): method(a, b) calculate(plus, 1, 2) # result: # 3
可以當(dāng)做函數(shù)的返回值
# 這也是裝飾器的原理 def inner(): print("MetaTian") def deco(): print("decorating...") return inner my_func = deco() my_func() # result: # decorating... # MetaTian
對(duì)象的3個(gè)屬性
身份:在內(nèi)存中的地址是多少,可用id()函數(shù)查看
類型:是什么類型的對(duì)象,可用type()函數(shù)查看
值:對(duì)象中的內(nèi)容是什么
type object和class的關(guān)系
type和class
關(guān)系:type -> class -> obj,obj是我們平時(shí)使用的對(duì)象,它由class對(duì)象生成,可以是我們自定義的類,也可以是內(nèi)建的類。上面說了,一切皆對(duì)象,class也是以type為模板,生成的對(duì)象。
type()函數(shù),當(dāng)傳入一個(gè)參數(shù)時(shí),返回對(duì)象的類型。傳入三個(gè)參數(shù)時(shí),用來生成一個(gè)類。
print(type(1)) print(type(int)) # result: # <class 'int'> # <class 'type'> class Person: pass student = Person() print(type(student)) print(type(Person)) # result: # <class '__main__.Person'> # <class 'type'> print(type(type)) # result: # <class 'type'>
type是以它自己為類生成的一個(gè)對(duì)象。如果熟悉靜態(tài)語言,這似乎并不好理解,但是對(duì)動(dòng)態(tài)語言來說就是這么自然。
object
object是最根本的一個(gè)基類,如果自己定義的類沒有顯示地去繼承某一個(gè)類,則它會(huì)自動(dòng)繼承object。上面討論的是類和對(duì)象之間的關(guān)系,現(xiàn)在要討論的是類和類之間的關(guān)系。
class Person: pass class Student(Person): pass print(Student.__bases__) print(Person.__bases__) print(int.__bases__) print(object.__bases__) # result: # (<class '__main__.Person'>,) # (<class 'object'>,) # (<class 'object'>,) # () print(type.__bases__) print(type(object) # result: # (<class 'object'>,) # <class 'type'>
type是一個(gè)類,它繼承的是object,object作為一個(gè)對(duì)象又是以type為類型生成的。
關(guān)于為什么Python中一切皆對(duì)象問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。