題目全部來自於網絡,答案爲個人解答和收集,因此不保證其正確和完備性,寫此文是爲了整理下之前學過的知識點,作複習爲之。
希望能夠和大家一起討論下有關Python的問題,但博主不承擔任何人因採用本文內部分或完全內容而帶來的任何損失。
1,是否知道動態語言(Python)中的鴨子類型?
- #“當看到一隻鳥走起來像鴨子、游泳起來像鴨子、叫起來也像鴨子,那麼這隻鳥就可以被稱爲鴨子。”
- #The idea is that you don't need a type in order to invoke an existing method on an object - if a method is defined on it, you can invoke it. The name comes from#the phrase "If it looks like a duck and quacks like a duck, it's a duck".
鴨子類型(duck typing)是動態類型的一種風格。在這種風格中,一個對象有效的語義,不是由繼承自特定的類或實現特定的接口,而是由當前方法和屬性的集合決定。在鴨子類型中,關注的不是對象的類型本身,而是它是如何使用的。
鴨子類型在Python中被廣泛使用。Python術語表這樣定義鴨子類型:
'''Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it must be a duck.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs the EAFP (Easier to Ask Forgiveness than Permission) style of programming.'''
更多地解釋...
2,是否知道可變參數與關鍵字參數?
可變參數也稱可變長度的參數,因爲我們在一些函數處理可變數量參數的情況。Python中使用*和**來指定元組和字典元素作爲可變參數。
- def foo(arg1,arg2,*nkw,**kw):
- print 'arg1 is: ', arg1
- print 'arg2 is: ', arg2
- for eachNKW in nkw: print 'arg: ', eachNKW
- for eachKW in kw.keys(): print "key arg '%s': '%s'" %(eachKW,kw[eachKW])
- #for example
- a_tuple=('x','y','z')
- a_dict={'A':10,'B':20}
- foo(1,2,3,4,5,lang='Python',ver=2.7,*a_tuple,**a_dict)
關鍵字參數僅針對函數調用,可以讓調用者以參數名來區分參數,這樣解釋器可以按給出的關鍵字達到匹配參數值的目的
- def foo(x):
- print x
- foo(23);foo('chain') #標準調用
- foo(x=23);foo(x='chain') #關鍵字調用
3,對函數式編程是否有初步瞭解?
關於函數式編程,可以先參考這篇入門級文章。
不過Python不是也不大可能成爲一門函數式編程語言。但是依然支持一些函數式語言的特性
比如匿名函數(利用關鍵字lambda創建),並且有些常用的函數,如map(),filter(),reduce()
4,是否知道列表生成式?
列表表達式,是列表解析的一種擴展。
列表解析:[expr for iter_var in iterable if cond_expr]
列表表達式:(expr for iter_var in iterable if cond_expr)
使用列表表達式可以避免創建列表,它並不真正創建列表,而是返回一個生成器。這個生成器在每次計算出一個條目後,把這個條目yield出來。 生成器表達式使用了azy evaluation,只有在檢索時才被賦值,所以在列表比較長的情況下使用內存上更有效。這樣可以更節省內存,提高執行效率。
5,是否知道lambda/decorator/slots?
lambda,即關鍵字用來創建匿名函數。
- def add(x,y): return x+y '''''等價於''' lambda x,y: x+y
lambda函數可以接受任意個參數,包括可選參數,但是表達式只有一個。可以把lambda創建的一個函數(對象)賦值給一個變量(元組或列表)以後就可以隨時調用了。如果不這樣做,它則在運行的時候被創建出來,引用計數+1,然後沒有地方被引用,計數歸零後就會被自動回收掉了。
decorator,一般被稱之爲裝飾模式,是用來擴展已有的功能。
在Python中即函數修飾符。可以把一個函數應用到另一個函數對象上,而且新函數對象依然綁定原來的變量。用法也很簡單,只要將@函數名放在需要裝飾的函數上面,就能夠裝飾了。
比較常見的就是把原來的函數裝飾成類函數或靜態函數
- class C:
- def foo(args): pass
- f = staticmethod(f)
- class C:
- @staticmethod
- def foo(args):pass
decorator並且可以帶參數,比如:
- def deco(args):
- return len
- @deco
- def foo(x):
- return list(x)
- print foo('chain')
__slots__是一個類變量,由一序列型對象組成,由所有合法標識構成的實例屬性的集合來表示。任何試圖創建一個不在__slots__中的名字的實例屬性都會導致AttributeError異常。這樣就很好地控制了用戶隨意地動態增加實例屬性。可以想象成C++的private成員變量。
6,py文件在運行時會產生pyc文件,用於緩存編譯後代碼?[a.正確 b.錯誤 c.不完全正確]
Python在執行時,首先會將.py文件中的源代碼編譯成Python的byte code,然後再由Python Virtual Machine來執行這些編譯好的byte code。Python在執行完這些byte code後,會銷燬PyCodeObject,所以下次再次執行.py文件時,Python需要重新編譯源代碼,創建PyCodeObject,然後執行byte code。Python提供一種機制,保存編譯的中間結果,即byte code,或者更準確地說,保存PyCodeObject。事實上,Python確實提供了這樣一種機制——Pyc文件。當Python運行結束後,這些信息甚至還會被存儲在Pyc文件中。pyc文件中的PyCodeObject對象也是以一種嵌套的關係聯繫在一起的。(C)
7,python支持多線程,能夠單進程無縫發揮多路CPU的優勢[a.支持,能夠 b.支持,不能夠 c.不支持,能夠 d.不支持,不能夠]
(B)
8,在python中,使用for從列表中刪除元素是錯誤的做法,會導致___________。正確的做法是使用python內置的____________函數。
有可能導致IndexError,但也有可能完成刪除的操作。正確做法是用filter(IsOdd,a_list)
9,改正以下程序中的錯誤,並寫出結果(禁止使用python運行)
- a=10
- def test (*b):
- print (a,type(b));
- a = 20;
- print a;
- print b[0](b[0])
- if __name__ == "__main__":
- print test (*[test]);
2,第一次使用a應該加上關鍵字global,
3,函數最後一句會造成遞歸的棧溢出
10,題目要求同上題
- def wrap_info (f):
- b = {"b":10};
- def inner_func (*p, **k):
- print b['b'], p, k;
- b['b'] += 1;
- f(*p, **k);
- return inner_func;
- def info (s):
- print "func info: %s" % s;
- if __name__ == "__main__":
- f1 = wrap_info (info);
- f1 ("a");
- f2 = wrap_info (info);
- f1 ("b");
- f2 ("c");
11,補完以下函數,使得繼承此類的對象具有單例特性
class singleton (object):
""" 單例模式的實現 """
def __new__ (cls, **kargs):
""" """
(
- class singleton (object):
- __instance = None
- def __new__ (cls, **kargs):
- if not cls.__instance: #if '_instance' not in cls.__dict__:
- cls.__instance=super(singleton(cls, **kargs))
- return cls.__instance
12,yield通常在python中被用做生成器,但實際上,這一實現是一種被稱爲協程的多線程交互模式。請補全下面的代碼,使得兩個虛擬的線程能夠互相交互運行(允許python上機)
- def thread_1 ():
- for i in range (0, 10):
- print i;
- yield i;
- def thread_2 ():
- for i in range (20, 30):
- print i;
- yield i;
- def run (thread_pool):
- if __name__ == "__main__":
- thread_pool = [];
- thread_pool.append (thread_1 ());
- thread_pool.append (thread_2 ());
- run (thread_pool);
該題也爲多種答案,運行通過即可。
def run (thread_pool):
try:
while True:
for i in thread_pool:
i.next ();
except StopIteration:
pass
其他答案亦可,但結果不能交替出現不算分。未能捕獲StopIteration扣分