divnotes
Table of Contents
1 classes and objects
1.1 類成員和對象成員
類成員相當於C++中的static成員變量,實例成員是和C++中的成員變量對應的,如下是類 成員:
>>> class counter: ... count = 0 1 ... def __init__(self): ... self.__class__.count += 1 2 ... >>> counter <class __main__.counter at 010EAECC> >>> counter.count 3 0 >>> c = counter() >>> c.count 4 1 >>> counter.count 1 >>> d = counter() 5 >>> d.count 2 >>> c.count 2 >>> counter.count 2
1.2 特殊函數
函數名以兩個下劃線開始和結束的函數名爲特殊函數 如_setitem_和_getitem_是和[]操作相關聯的
class MyDict: def __init__(self): self.data = {} def __setitem__(self, k, v): self.data[k] = v print('__setitem__(',k,',',v,')') def __getitem__(self, k): print('__getitem__(',k,')=',self.data.get(k,0)) return self.data.get(k,0) d = MyDict() d[1] = 2 print(d[1])
1.3 私有函數
函數名以兩個下劃線開始且不是兩個下劃線結束的函數 變量名同樣遵循次規則
class PrivateFunc: def __init__(self): self.ary = [1,2,3] def __listAry(self): for i in self.ary: print(i) pf = PrivateFunc() try: pf.__listAry() except AttributeError as err: print('func not exist: ', err)
從程序看出,python其實是把函數名和變量名改名了,改名後的私有成員同樣是public的, 可以直接調用
Date: 2013-04-16 16:39:51 中國標準時間