我總結了python已下點:
面向對象
- 類和對象的創建
- 屬相相關
- 方法相關
- 元類
- 內置的特殊屬性
- 內置的特殊方法
PS注意:不管你是為了Python就業還是興趣愛好,記住:項目開發經驗永遠是核心,如果你缺新項目練習或者沒有python精講教程,可以去小編的Python交流.裙 :七衣衣九七七巴而五(數字的諧音)轉換下可以找到了,里面很多新教程項目,還可以跟老司機交流討教!
類和對象的創建
類
# 經典類 沒有繼承 object的類 # 新式類 繼承了 object的類 class Money: # 2.x中默認是經典類,3.x中是新式類 pass class Money(object): # 兼容的一種寫法 pass # Money既是類的__name__屬性名,又是一個引用該類的變量 print(Money.__name__) # Money xxx = Money print(xxx.__name__) # Money
對象
one = Money() print(one) # <__main__.Money object at 0x000001555E9534A8> print(one.__class__) # <class '__main__.Money'>
屬性相關
對象屬性
class Person: pass p = Person() # 給 p對象增加屬性, 所有的屬性好像是以字典的形式組織的 p.age = 18 print(p.age) # 18 print(p.__dict__) # {'age': 18} print(p.sex) # AttributeError: 'Person' object has no attribute 'sex' # 刪除p對象的屬性 del p.age print(p.age) # AttributeError: 'Person' object has no attribute 'age'
類屬性
class Money: num = 666 count = 1 type = "rmb" print(Money.num) # 666 # 對象查找屬性,先到對象自身去找,若未找到,根據 __class__找到對應的類,然后去類中查找 one = Money() print(one.count) # 1 # 不能通過對象去 修改/刪除 對應類的屬性 one.num = 555 print(Money.num) # 666 print(one.num) # 555 # 類屬性會被各個對象共享 two = Money() print(one.num, two.num) # 666 666 Money.num = 555 print(one.num, two.num) # 555 555
限制對象的屬性添加
# 類中的 __slots__屬性定義了對象可以添加的所有屬性 class Person: __slots__ = ["age"] # 只允許添加一個 age屬性 p1 = Person() p1.age = 1 p1.num = 2 # AttributeError: 'Person' object has no attribute 'num'
私有化屬性
-
Python沒有真正的私有化支持,只能用給變量添加下划線來實現偽私有;通過名字重整機制
-
屬性的訪問范圍:類的內部-->子類內部-->模塊內的其他位置-->其他模塊
-
公有屬性 x
- [x] 類的內部
- [x] 子類內部
- [x] 模塊內的其他位置
- [x] 子類內部
-
受保護屬性 _x
- [x] 類的內部
- [x] 子類內部
- [x] 模塊內的其他位置(但不推薦)
- [x] 子類內部(from ... import xxx 不可以訪問,要指明all變量)
-
私有屬性 __x
- [x] 類的內部
- [ ] 子類內部
- [ ] 模塊內的其他位置
- [ ] 子類內部(同_x)
-
保護數據案例
class Person: def __init__(self): self.__age = 18 def set_age(self, age): # 錯誤數據的過濾 if isinstance(age, int) and 0 < age < 150: self.__age = age else: print("Wrong age value") def get_age(): return self.__age p = Person() print(p.get_age()) # 18 p.set_age(22) print(p.get_age()) # 22
- 只讀屬性
# 1. 屬性私有化 + 屬性化 get()方法 class Person(object): def __init__(self): self.__age = 18 # 可以以使用屬性的方式來使用方法 @property def age(self): return self.__age p = Person() print(p.age) # 18 p.age = 666 # Attribute Error: can't set attribute # 2. 通過底層的一些函數 class Person: # 通過 屬性 = 值 的方式來給一個對象增加屬性時,底層都會調用這個方法,構成鍵值對,存儲在 __dict__字典中 # 可以考慮重寫底層的這個函數,達到只讀屬性的目的 def __setattr__(self, key, value): if key == "age" and key in __dict__: print("read only attribute") else: self.__dict__[key] = value
方法相關
方法的划分
- 實例方法
- 類方法
- 靜態方法
class Person: def instance_fun(self): # self: 調用對象的本身,調用時不用寫,解釋器會傳參 print("instance method", self) @classmethod def class_fun(cls): # cls: 類本身 print("class method", cls) @staticmethod def static_fun(): print("static method")
- 所有的方法都存儲在類中,實例中不存儲方法
- 類方法和靜態方法無法訪問實例屬性
方法的私有化
- 和變量的私有化思想差不多
class Person: __age = 18 def __run(self): # 只能在該類中被調用 print("running...")
元類
- 創建類對象的類(類也是一個對象)
a, s = 8, "123" print(a.__class__, s.__class__) # <class 'int'> <class 'str'> print(int.__class__, str.__class__) # <class 'type'> <class 'type'>
-
type是元類。
image -
通
type
元類來創建類,動態創建。也可以用__metaclass__
來指明元類,進行類的創建。- 檢測類對象中是否有metaclass屬性
- 檢測父類中是否有metaclass屬性
- 檢測模塊中是否有metaclass屬性
- 通過內置的
type
來創建類
def run(self): print("run...") Dog = type("Dog", (), {"count": 0, "run": run}) print(Dog) # <class '__nain__.Dog'> d = Dog() print(d.count) # 0 print(d.run()) # run...
內置的特殊屬性

image
內置的特殊方法
- 信息格式化操作
calss Person: def __init__(self, n, a): self.name = n self.age = a # 面向用戶 def __str__(self): return "name: %s, age: %d" % (self.name, self.age) # 面向開發人員 def __repr__(self): # todo # 一般默認給出對象的類型及地址信息等 # 打印或進行格式轉換時,先調用 __str__()函數,若未實現,再調用 __repr__()函數 p = Person("Rity", 18) print(p) # name: Rity, age: 18 res = str(p) print(res) # name: Rity, age: 18 print(repr(p)) # <__main__.Person object at 0x000001A869BEB470>
- 調用操作
# 使得一個對象可以像函數一樣被調用 class PenFactory: def __init__(self, type): self.type = type def __call__(self, color): print("get a new %s, its color is %s" % (self.type, color)) pencil = PenFactory("pencil") pen = PenFactory("pen") # 一下兩種使用方式會調用 __call__()函數 pencil("red") # get a new pencil, ites color is red pencil("blue") # get a new pencil, ites color is blue pen("black") # get a new pen, ites color is black
- 索引操作
class Person: def __init__(self): self.cache = {} def __setitem__(self, key, value): self.cache[key] = value def __getitem__(self, key): return self.cache[key] def __delitem__(self, key): del self.cache[key] p = Person() p["name"] = "Rity" ...
- 比較操作
# 使得自己定義的類可以按照一定的規則進行比較 import functools @functools.total_ordering class A: def __init__(self, age, height): self.age = age self.height = height def __eq__(self, other): # == return self.age == other.age def __lt__(self, ohter): # < return self.age < other.age a1, a2 = A(18, 170), A(19, 178) # 因為邏輯具有相反性,當使用 > 時,首先會查找 __gt__()函數,若未定義,將參數交換后調用 __lt()__方法 # 由 == 和 < 可以組合出其他的所有比價邏輯,使用裝飾器可以自動生成其他邏輯對應的函數,簡化代碼 print(a1 < a2) # True print(a2 > a1) # True print(a1 >= a2) # False
最后提醒大家不管你是為了Python就業還是興趣愛好,記住:項目開發經驗永遠是核心,如果你缺新項目練習或者沒有python精講教程,可以去小編的Python交流.裙 :七衣衣九七七巴而五(數字的諧音)轉換下可以找到了,里面很多新教程項目,還可以跟老司機交流討教!
本文的文字及圖片來源於網絡加上自己的想法,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理。