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 (這三個不寫,考驗我的記憶)

2009年12月27日 星期日

寫程式與切蔥花

 
C/C++一直是我吃飯的工具,
從唸書到工作都是。

有時候也會去接觸沒碰過的程式語言,
例如研究所時摸過一點Perl,
受訓時看過一些PHP,
工作之後有看過Java,
前些時候則寫了一些Python......
(意思就是這些東西都如過客般,曇花一現,現在已經不知道忘到哪裡去了)

有人看到就會覺得我好上進,
願意花時間和精力去學習工作以外的東西,
覺得我很適合走這一行。
我有碰過對程式很有興趣,也很有天份的傢伙,
可是我不是。

也許只是好奇心作祟,
想看看不同的語言之間有什麼差異性。
也許只是懶人天性,
想說先學說不定以後會用到,就不用再學了。
也可能是異想天開,
以為學了什麼殺手級的語言,
可以靠它接案子,賺外快。

但是我對它真的不那麼有興趣。
我只是想做好份內的事情,
coding是我份內的事情,所以我要努力做到最好,
就這樣而已。
假設我今天是機車行師傅或是餐廳的廚師,
我也會把相關技能練到純熟。

最近蔥很便宜,一大把才30塊新台幣。
因為知道蔥的冷凍保存法,
所以就去買了一把,
然後很高興地回家處理。
那一個下午,
揀蔥,洗蔥,切蔥,
現在冰箱冷凍庫都是我處理好的蔥段和蔥花(哈),這樣其實也很快樂。
跟寫程式比起來,
說不定我比較喜歡切蔥花(泣)。

2009年12月24日 星期四

每天充滿,即是訓練(轉載)

每天充滿,即是訓練

這篇文章喚起了我沉睡已久的記憶。
在關西受訓時,
有一次上課,
講師說了一段話:

成功不是靠天份,而是靠每天執行該做的事。

"每天"何其重要,卻又何其困難。
需要極大的毅力及堅持,
能做到者必能歡喜收穫。

2009年12月21日 星期一

送阿媽的最後一程

傳統上,長孫是要"捧斗"。
告別式那一天,我坐在靈車的前座,
腳上放著"斗",雙手緊緊環繞。

車一邊開,要一邊跟奶奶說:
我們要出發囉...要轉彎囉...要過橋囉...阿媽跟好喔...阿媽不要怕...我們快到囉...
好像抱著的是一個小嬰兒。

是啊,當初剛到這個世界上時,
奶奶就是這樣抱著我的吧,
就是這樣諄諄提醒的吧。
現在,奶奶離開這個世界,
換我用同樣的方式抱著她,輕聲提醒。

止不住的眼淚一直持續到告別式結束。

附註(2009/12/17告別式,10天前奶奶放下了一切痛苦)