https://github.com/taizilongxu/interview_python
?
1 Python的函數參數傳遞
strings, tuples, 和numbers是不可更改的對象,而list,dict等則是可以修改的對象
?
2 Python中的元類(metaclass)
3 @staticmethod和@classmethod
python 三個方法,靜態方法(staticmethod),類方法(classmethod),實例方法
4 類變量和實例變量
類變量就是供類使用的變量,實例變量就是供實例使用的.
若是list,dict修改實例變量,類變量也改變。strings, tuples, 和numbers是不可更改的對象,故實例變量和類變量不同。
5 Python自省
自省就是面向對象的語言所寫的程序在運行時,所能知道對象的類型.簡單一句就是運行時能夠獲得對象的類型.比如type(),dir(),getattr(),hasattr(),isinstance().
?
6 字典推導式
列表推導式(list comprehension)
In [39]: [x*x for x in range(10)]
Out[39]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2.7加入字典推導式
>>> strings = ['import','is','with','if','file','exception']??
??
>>> D = {key: val for val,key in enumerate(strings)}??
??
>>> D??
{'exception': 5, 'is': 1, 'file': 4, 'import': 0, 'with': 2, 'if': 3}??
7 單下劃線、雙下劃線
http://stackoverflow.com/questions/1301346/what-is-the-meaning-of-a-single-and-a-double-underscore-before-an-object-name
single underscore :?private
>>> class MyClass(): ... def __init__(self): ... self.__superprivate = "Hello" ... self._semiprivate = ", world!" ... >>> mc = MyClass() >>> print mc.__superprivate Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: myClass instance has no attribute '__superprivate' >>> print mc._semiprivate , world! >>> print mc.__dict__ {'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}
8 字符串格式化:%和.format
sub1 = "python string!" sub2 = "an arg"a = "i am a %s" % sub1 b = "i am a {0}".format(sub1)c = "with %(kwarg)s!" % {'kwarg':sub2} d = "with {kwarg}!".format(kwarg=sub2)print a # "i am a python string!" print b # "i am a python string!" print c # "with an arg!" print d # "with an arg!""hi there %s" % (name,) # supply the single argument as a single-item tuple
9 迭代器和生成器
10?*args
?and?**kwargs
*args,
例如,它可以傳遞任意數量的參數. ?You would use?*args
?when you're not sure how many arguments might be passed to your function
**kwargs,
允許你使用沒有事先定義的參數名.
*args表示任何多個無名參數,它是一個tuple;**kwargs表示關鍵字參數,它是一個dict。
https://stackoverflow.com/questions/3394835/args-and-kwargs/3394898#3394898
def foo(*args, **kwargs):print 'args = ', argsprint 'kwargs = ', kwargsprint '---------------------------------------'if __name__ == '__main__':foo(1,2,3,4)foo(a=1,b=2,c=3)foo(1,2,3,4, a=1,b=2,c=3)foo('a', 1, None, a=1, b='2', c=3)
輸出結果如下:
args =? (1, 2, 3, 4)?
kwargs =? {}?
---------------------------------------?
args =? ()?
kwargs =? {'a': 1, 'c': 3, 'b': 2}?
---------------------------------------?
args =? (1, 2, 3, 4)?
kwargs =? {'a': 1, 'c': 3, 'b': 2}?
---------------------------------------?
args =? ('a', 1, None)?
kwargs =? {'a': 1, 'c': 3, 'b': '2'}?
---------------------------------------
?
# 當調用函數時你也可以用 * 和 ** 語法 def star_operation(name, value, count):print("Name: {}, Value: {}, Count: {}".format(name, value, count))if __name__ == "__main__":# 它可以傳遞列表(或者元組)的每一項并把它們解包. 注意必須與它們在函數里的參數相吻合a_list = ["名字", "值", "計數器"]a_dict = {'a':1, 'b':2, 'b':3}star_operation(*a_list)star_operation(**a_dict.items())
輸出:
**后面必須是 mapping,映射
?
11 面向切面編程AOP和裝飾器
裝飾器的作用就是為已經存在的對象添加額外的功能
# how decorators workdef makebold(fn):def wrapped():return "<b>" + fn() + "</b>"return wrapped def makeitalic(fn):def wrapped():return "<i>" + fn() + "</i>"return wrapped@makebold @makeitalic def hello():return "hello world"print hello() ## returns "<b><i>hello world</i></b>"
函數即是對象
def shout(word="yes")return word.capitalize()+"!"print (shout()) # Yes!# As an object, you can assign the function to a variable like any other object scream = shout# Notice we don't use parenthese: we are not calling the fuction, # we are putting the function "shout" into the variable "scream". # It means you can then call "shout" from "scream": print (scream()) # Yes!# More than that, it means you can remove the old name 'shout', # and the function will still be accessible from 'scream'del shout try:print(shout()) except NameError, e:print(e) # "name 'shout' is not defined"print(scream()) # Yes!
python: function can be defined inside another function / 函數能夠定義在其他函數內。
Functions references:
1.can be assigned to a varible
2.can be defined in another function
def getTalk(kind="shout"):# We define functions on the flydef shout(word="yes"):return word.capitalize()+"!"def whisper(word="yes") :return word.lower()+"...";# Then we return one of themif kind == "shout":# We don't use "()", we are not calling the function, we are returning the function objectreturn shout else:return whisper# How do you use this strange beast?# Get the function and assign it to a variable talk = getTalk() # You can see that "talk" is here a function object: print(talk) #outputs : <function shout at 0xb7ea817c># The object is the one returned by the function: print(talk()) #outputs : Yes!# And you can even use it directly if you feel wild: print(getTalk("whisper")()) #outputs : yes...
Decorator :
'wrappers', let you execute code before and after the function they decorate without modifying the function itself.
?
methods and functions are really the same. The only difference is that methods expect that their first argument is a reference to the current object (self
).
方法和函數的唯一區別是,方法的第一個參數是對當前對象的引用,self.
?
Python自帶的幾個裝飾器:property,staticmethod。。
Django 使用裝飾器來管理緩存和權限控制。
Twisted 用來實現異步調用。
?
12 鴨子類型
鴨子類型是動態類型的一種風格,在這種風格中,一個對象有效的語義,不是由繼承自特定的類或實現特定的接口,而是由當前 方法和屬性的集合所決定。
例如,在不使用鴨子類型的語言中,我們可以編寫一個函數,它接受一個類型為鴨的對象,并調用它的走和叫方法。在使用鴨子類型的語言中,這樣的一個函數可以接受一個任意類型的對象,并調用它的走和叫方法。如果這些需要被調用的方法不存在,那么將引發一個運行時錯誤。任何擁有這樣的正確的走和叫方法的對象都可被函數接受的這種行為引出了以上表述,這種決定類型的方式因此得名。
?
?
網絡
5 Post和Get
區別:
一個用于獲取數據,一個用于修改數據。
?