我个人不是很喜欢python。日常使用ruby比较多,正好对比一下。首先提个醒,以下仅代表个人意见。
python和ruby对比一下,python赢在了哪里呢?用的人多所以库多
性能好一点
语法元素比较少,学习相对简单
python相比ruby要来的简单,但是它是一把双刃剑,既降低了学习成本,又造成了表现力和元编程能力的不足。
在我个人看来,需要用更多的时间学习的ruby比python的语法更优美、表现力更强、元编程能力更强,这也就导致了一个结果--在代码复用能力和解耦能力上,python会完全地输给ruby
这里举个很小的例子,在802.11标准中使用的PRF函数,有人用python这样去写:
def PRF(key,prefix,data,length_in_bits):
""" Key, prefix and data are arbitrary strings, the parameterlength_in_bits and must be multiple of 8."""
R = ''
for i in range((length_in_bits+159)/160):
hmac_sha_1 = hmac.new(key, prefix + chr(0x00) + data + chr(i),sha)
R = R + hmac_sha_1.digest() # concatenate latest hast to result string
return L(R,0,length_in_bits) # return R truncated to 'length'
def L(I,F,L):
""" Take from I starting from the left, bit F for L bitsmoving to the right using 7.1.1 bit convention from IEEE 802.11."""
# This implementation only works on byte boundaries.
assert (F % 8 == 0) and (L % 8 == 0), 'can only truncate on byte boundaries'
return I[(F/8):((F/8)+(L/8))]
然后我们需要PRF_128 PRF_256等等,作者这样去写:
def PRF_128(key,A,B): return PRF(key,A,B,128)
def PRF_192(key,A,B): return PRF(key,A,B,192)
def PRF_256(key,A,B): return PRF(key,A,B,256)
def PRF_384(key,A,B): return PRF(key,A,B,384)
def PRF_512(key,A,B): return PRF(key,A,B,512)
def PRF_768(key,A,B): return PRF(key,A,B,768)
在ruby里,这样是会笑掉大牙的。我们从来不会这么去写,而是这样去写:
首先,把这些函数封装到一个模块里,python没有模块,但模块其实没什么特别的,它是一个不能继承、不能例化的类。
module Prf
def prf(key,prefix,data,length_in_bits)
end
def L(I,F,L)
end
end
然后是重点,我们如何得到那一大堆PRF_呢?
这样去做:
module Prf
def method_missing(name, *args, &block)
return prf(args[0], args[1], args[2], $1) if name ~= /^prf_([0-9]+)/
super
end
end
这样比python要优雅很多。