Python中一切皆對象
和Java相比,Python的面向對象更加徹底。
函數和類也是對象,是python的一等公民。
代碼和模塊也可以稱之為對象。
python中的類也是對象,類可以理解為模板,根據這個模板去生成我們的對象,可以動態修改類的屬性。
何為一等公民?
- 可以賦值給一個變量
- 可以添加到集合對象中
- 可以作為參數傳遞給函數
- 可以當做函數的返回值 (生成器應用)
type、object、class之間的關系
類是由type來生成的一個對象,object是所有類都要繼承的最頂層的一個基礎類,type也是一個類,同時也是一個對象。
看代碼片段一:
a = 1
b = "abc"
print(type(1))
print(type(int))
print(type(b))
print(type(str))
打印出的結果:
<class 'int'>
<class 'type'>
<class 'str'>
<class 'type'>
代碼片段二:
class Student:
pass
class MyStudent(Student):
pass
stu = Student()
print(type(stu))
print(type(Student))
print(int.__bases__)
print(str.__bases__)
print(Student.__bases__)# 打印Student基類
print(MyStudent.__bases__)# 打印Student基類
print(type.__bases__)
print(object.__bases__) # 最頂層的類的基類為空
print(type(object))
打印出的結果:
<class '__main__.Student'>
<class 'type'>
(<class 'object'>,)
(<class 'object'>,)
(<class 'object'>,)
(<class '__main__.Student'>,)
(<class 'object'>,)
()
<class 'type'>
可以看到,類是由type來生成的一個對象。
上述代碼建議反復閱讀練習。
Python中常見的內置類型
首先說明對象的三個特征:
- 身份:也就是地址,通過id()函數查看地址
- 類型:int、str等
- 值:每個對象都有自己的值
常見內置類型:
- None(全局只有一個),Python解釋器在啟動時會用None生成一個None對象。
a = None
b = None
print(id(a) == id(b))
打印結果:
Ture
可以看到a,b是指向同一個對象(id相同)。
- 數值類型:int float complex(復數) bool。
- 迭代類型:可用for進行遍歷
- 序列類型:list、bytes、range、tuple、str、array 等
- 映射類型:dict
- 集合類型:set、frozenset
- 上下文管理器:with語句
- 其他:class、實例 等等等。
Python中的魔法函數
問:什么是魔法函數?
答:雙下劃線開頭,雙下劃線結尾的這些函數,通常稱之為魔法函數。
例如:
一般魔法函數不要自定義,使用 Python 提供的即可。
使用 Python 提供的魔法函數,為了增強類的特性。
代碼:使用魔法函數之前
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
company = Company(["tom", "bob", "jane"])
for i in company.employee:
print(i)
打印結果:
a
b
c
代碼:使用魔法函數之后
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
def __getitem__(self, item):
return self.employee[item]
company = Company(["a", "b", "c"])
打印結果:
a
b
c
可以看到__getitem__()
這個魔法函數的功能。
定義了這個魔法函數后,實例化后的對象就隱含的變為可迭代對象(iterable)。
for循環其實是要拿到一個對象的迭代器,迭代器是需要實現__iter__
這個方法才會有迭代器特性,Python語法會做一些優化,如果拿不到迭代器,就會嘗試去對象中找__getitem__
這個方法,如果有的話就會調用這個方法,一次一次直到將數據取完。這是python語言本身解釋器會完成的功能。
魔法函數調用不需要顯示調用,解釋器會隱式調用。
Python的數據模型
魔法函數是Python數據模型的一個概念而已,因為網絡上大家喜歡稱之為魔法函數。
Python數據模型會增強對象的特性。
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
def __getitem__(self, item):
return self.employee[item]
def __len__(self):
return len(self.employee)
company = Company(["a", "b", "c"])
print(len(company))
結果:
3
__len__
魔法函數增強了company對象的特性。
因為魔法函數很多,類似的魔法函數請大家自行去網上查找,并查看用法。
可以關注我的微信公眾號,會更新Python知識點,也會有其他語言和軟件開發中的各種坑,都會記錄在公眾號。