1. 程式人生 > >Python面向物件程式設計基礎學習筆記

Python面向物件程式設計基礎學習筆記

類名大寫開頭;

建構函式

class Obj(Object)
nouse = "helo"  #類變數,例項共享(類似每個例項複製了一份,而不是static成員), 無法在函式中直接訪問到,可以用self.nouse訪問
dict = {"k":"ve"}  # 這個是所有例項共享的, 例項一個修改會影響到其他例項的dict(每個例項支拷貝了指標?)
def __init__(self, args):
self.name = ....  #成員屬性
def __del__(self):  #類似析構
...

成員函式:

def mem_fun(self)
:
... @staticmethod #類似靜態函式,無法用例項物件.來呼叫 def test(self): print("talk") @property def name(self): return self.name

所有的函式都要有self引數, 作用如同this指標; self代表例項本身;
如:
O.mem_fun() ⇒ Obj.mem_fun(O)
@property 代表屬性, 雖然是成員函式,但呼叫的時候只能以成員屬性的方式呼叫,不能像函式一樣呼叫;
O.name # ⇒ name

私有函式

def __sFunc
(self):
#兩個下劃線 ...

私有屬性

self.__sV = 5  #兩個下劃線: 私有

# 強制呼叫私有

print(O._Obj__sV  )

繼承

class Animal(Object):
def __init__(self, arg1):
...

#子類

class People(Animal):  #基類名字作為引數
def __init__(self, arg1, arg2):  # 額外引數加入後面
Animal.__init__(self, arg1)
self. v2 = arg2


#預設引數

def __init__
(self,arg1,arg2,age=20,country='china'):
self.arg1=arg1 self.arg2=arg2 self.age=age self.country=country #使用時: People(arg1,arg2,'american') #這時'american'是賦給了age的(動態型別的原因), country 是預設的'china'; 可以使用命名引數的形式: country = 'american' People(arg1,arg2,country = 'american' )

多重繼承

加上一個新類:

class Career(object):
   def __init__(self, Id):
       pass

#繼承

class People(Animal, Career):  # 直接寫這
 def __init__(self, arg1):
   Animal.__init__(self, arg1)
   Career.__init__(self)  # 引數問題怎麼解決?
 def P(self):
   print("the out is %s, %s " % ())

測試與import分離

if __name__=='__main__':
  # test code typing here,   will not run when imported as a  module 

類例項的儲存到資料庫

把例項儲存到資料庫中, 即便程式結束了, 以後仍然可以使用;
工具; Pickle, Shelve

Shelve使用;

  1. 如上面的類儲存在people.py檔案裡;
  2. 現在在另一個檔案中生成幾個例項:
    
    #"store.py"
    
    from people import People  #匯入People類
    laowang = People("lao", "wang", 20)
    xiaoming = People("xiao","ming",30)
    
    
    #上面生成了2個例項, 下面將通過shelve儲存例項到檔案中
    
    import shelve
    db = shelve.open('pl')
    for obj in (laowang, xiaoming):
       db[obj.name] = obj
    db.close()

執行後就會在檔案交下生成三個檔案:pl.dir, pl.dat, pl.bak;
使用時,仍然通過shelve來操作, 如下面是命令列操作(People類所在的檔案要和到處的例項檔案在一起, 或相關路徑才能搜尋到):

import shelve
db = shelve.open('pl')
list(db.keys())  # ⇒ ['laowang', 'xiaoming']
lw = db['laowang']
lw.info()  # 呼叫方法

多型

基類中定義的函式可以被子類覆蓋; 函式都是類似虛擬函式的形式,所以子類呼叫時, 呼叫的是子類的函式;

class base:
 def __init__(self):
   pass
 def delegete(self):
   self.action() #action函式可以不在父類定義, 但如果同時沒在子類定義則會出現錯誤
 def action(self):
   assert False, " no defined in derive class"
 class derive:
   def __init__(self):
     pass
   def action(self):
     print("action is done in derive") 

上面的例子中,如果derive類中沒有定義action函式則會呼叫base中的action, 此時會直接觸發崩潰;

抽象類

抽象類和C++中的概念一樣,無法生成例項

'''  this is the specifying words as the __doc__ attribute of module '''
from abc import ABCMeta, abstractmethod
class Super(metaclass=ABCMeta)
''' this is the class specifying words '''
@abstractmethod
def method(self):  pass  # 純虛擬函式

用@abstractmethod聲明瞭的函式必須在子類中實現;