Python 學習筆記 5

2021-06-21 06:08:03 字數 2075 閱讀 9146

今天從25章開始(p652)學習 python 的 oop

用**看起來更直觀:

class class_a:

def __init__(self,value): # 建構函式

self.data = value

def __add__(self,other): # 運算子過載

return class_a(self.data +other)

def __str__(self): # 運算子過載

return '[class_a : %s]'% self.data

def do_something(self,percent): # 方法

self.data *= (1.00 + percent)

class class_b(class_a): # 繼承(多基類繼承!)

def __init__(self,value):

class_a.__init__(self,value) # 顯式實現

def do_something(self,percent): # 覆蓋基類方法

self.data *= (1.00 - percent)

class class_c(class_b):

def __init__(self,value):

self.data = value

def __str__(self): # 覆蓋基類運算子過載

return '[class_c] : %s]' % self.data

c_a = class_a(100)

c_b = class_b(200)

c_c = class_c(300)

c_a.do_something(0.10) # c_a.data = 100 * 1.10 = 110

print(c_a)

c_a_add = c_a + 10.00 # 運算子過載,返回新的 class_a , c_a.data = 110 +10 = 120

print(c_a_add)

c_b.do_something(0.20) # c_b.data = 200 * 0.80 = 160

print(c_b)

c_c.do_something(0.30) # c_c.data = 300 * 0.70 = 210

print(c_c)

>>> 

[class_a : 110.00000000000001]

[class_a : 120.00000000000001]

[class_a : 160.0]

[class_c] : 210.0]

>>>

(精度問題可以再看看 數字 型別)

一、python 中的類可以多基類繼承

二、由於python是動態語言,所以類的屬性、方法可以在執行時動態裝配

三、不用解釋,python 天生支援多型

四、python 不需要 inte***ce ,每個物件都是自描述的,不需要畫蛇添足的再弄出個 inte***ce 出來

五、python 同樣不需要抽象類......

六、進行企業開發可能用到的東西

1、gui: pyqt、wxpython

2、web:django、turbogears、pylons、web2py、zope

3、資料庫:

oodb:zodb

erdb:mysql、postgresql、sqlite

4、orm: sqlobject、sqlalchemy

小結:除了很多概念,c#的經驗在 python 中沒有多少幫助,反而十幾年前用vfp的很多東西回想起來了......

下午從第28章開始

Python學習筆記5

列表與元組的區別 sort sort reverse true 對元素進行排序,預設是公升序,小值在前面,後面那種形式是降序,小值在後面 reverse 反轉列表的順序 count value 返回value的出現次數 index value 返回value第一次出現的位置編號 insert i,v...

Python學習筆記 5

模組 用來從邏輯上組織python 包括變數,函式,類,邏輯等,來實現乙個功能。本質就是乙個python檔案。包 從邏輯上組織模組。必須帶有乙個init.py檔案 匯入方式 import module import module1,module2 from module import 不建議用 fr...

Python學習筆記 5

python學習筆記 5 標準庫函式 python提供了很多標準庫函式,用於完成很多通用任務。之前已經用過input raw input range 等函式。一些庫函式已經在python直譯器中內建,因此可以直接呼叫。還有很多庫函式則放在模組下的檔案中。這些模組在安裝python時已一併複製,要呼叫...