2009年12月31日 星期四

byte of python 小筆記

 
雖然已經寫過一些小程式,
最近還是強迫自己把"byte of python"看了一次,
看看是不是有什麼遺漏的部份。

1. 不定參數

python 也有不定參數的用法,
其中分為 list 和 dictionary

#!/usr/bin/python
# Filename: total.py
def total(initial=5, *numbers, **keywords):
    count = initial
    for number in numbers:
        count += number
    for key in keywords:
        count += keywords[key]
    return count

print(total(10, 1, 2, 3, vegetables=50, fruits=100))


其中,
10, 1, 2, 3會被當成 list 傳進函式中,

vegetable=50, fruit=100會被當成 dictionary 傳進函式中。

2. Tuple

Tuple 跟 list 很類似,但是功能沒有那麼多,最重要的差異是,tuple 是不可變的 (immutable),
定義 tuple 的方式是用小括號對 (parentheses)

zoo = ('python', 'elephant', 'penguin')

那麼如何定義空的或是只有一個元素的 tuple 呢?

# 空的tuple:
myempty = ()

# 只有一個元素的tuple:
singleton = (2, )

3. Set

python內建的資料結構除了 list, tuple,dictionary 外,
還有一種就是 set。

set裡面沒有順序,每個元素也沒有數量,
而最好用的莫過於集合的交集,聯集,差集之類的運算。

4. The format Method

有時候我們需要把字串跟一些資訊結合在一起,format 是很好的方法。

age = 25
name = 'Swaroop'
print('{0} is {1} years old'.format(name, age))
print('Why is {0} playing with that python?'.format(name))

進階用法 :
>>> '{0:.3}'.format(1/3) # decimal (.) precision of 3 for float
'0.333'
>>> '{0:_^11}'.format('hello') # fill with underscores (_) with the text
centered (^) to 11 width
'___hello___'
>>> '{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python')
# keyword-based
'Swaroop wrote A Byte of Python'



5. Object Oriented (class)

self 就等同於C/C++中的 this 指標。

==
而__init__就等同C/C++中的建構子,
    __del__就等同C/C++中的解構子。

這兩個 method 都是自動被呼叫的,
其中__init__當然是物件建立時會被呼叫,
__del__是當物件不再被使用時會被呼叫,
但是不保證何時__del__會被呼叫,
所以我們也可以強制使用 del 來呼叫它。

==
python 的類別也有 static method,
有兩種用法
一種是像一般 method 一樣宣告,
但呼叫時加上 staticmethod(),例如

def howMany():
    '''Prints the current population.'''
    print('We have {0:d} robots.'.format(Robot.population))
howMany = staticmethod(howMany)

另一種是宣告時就加上裝飾字 (@staticmethod)

@staticmethod
def howMany():
'''Prints the current population.'''
print('We have {0:d} robots.'.format(Robot.population))


==
在 python 中,
所有的 class members 都是 public,而所有的 class methods 都是 virtual,
那如果需要 private 的 class member 呢?
只要在變數前加兩個底線就可以了,
像是 __privatevar 。

==
python 是支援多重繼承的,
在繼承的情況下,
如果有找不到的 method,
它也會往 base class 去找喔。

6. Pickle Module

有一個沒用過的東東,pickle,
pickle可以把任何物件存成檔案,
當然也可以從檔案載入,
哇屋,這真是超有用的 :)

#!/usr/bin/python
# Filename: pickling.py

import pickle

# the name of the file where we will store the object
shoplistfile = 'shoplist.data'
# the list of things to buy
shoplist = ['apple', 'mango', 'carrot']

# Write to the file
f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f) # dump the object to a file
f.close()

del shoplist # destroy the shoplist variable

# Read back from the storage
f = open(shoplistfile, 'rb')
storedlist = pickle.load(f) # load the object from the file
print(storedlist)


7. Logging Module

當我們想把一些除錯訊息輸出到檔案時,
這個模組就非常好用了。
只要給檔案路徑跟基本設定就可以了。

#!/usr/bin/python
# Filename: use_logging.py
import os, platform, logging
if platform.platform().startswith('Windows'):
    logging_file = os.path.join(os.getenv('HOMEDRIVE'),
    os.getenv('HOMEPATH'), 'test.log')
else:
    logging_file = os.path.join(os.getenv('HOME'), 'test.log')

logging.basicConfig(level=logging.DEBUG,
     format='%(asctime)s : %(levelname)s : %(message)s',
     filename = logging_file,
     filemode = 'w',
)
logging.debug("Start of the program")
logging.info("Doing something")
logging.warning("Dying now")


8. List Comprehension

這真的是很"技巧性"的寫法。

listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listtwo)


9. 其他

exec, eval, repr (這三個不寫,考驗我的記憶)

沒有留言:

張貼留言