python中start用法_Start Python 学习笔记(琐碎知识,持续更新。。。)
最近比較閑,想學習一門腳本語言,于是選擇了python進行學習,之前對腳本語言不是很熟悉,所以不對python好壞做任何評價。希望通過學習python,能讓自己對腳本語言有更深刻的認識吧。
Python的執行過程:當程序執行時,python內部會先將源代碼編譯成所謂的字節碼的形式。字節碼是源代碼底層的、與平臺無關的表現形式。編譯字節碼的過程中,會生成一個.pyc的文件,這個文件就是編譯之后的字節碼。Python真正在運行的就是這個字節碼文件,如果生成字節碼文件之后沒有再修改過源代碼的話,下次程序運行會跳過編譯這個步驟,直接運行pyc文件,這是一種啟動速度的優化。字節碼文件被發送到python虛擬機(Python Virtual Machine, PVM)上來執行。PVM是python的運行引擎。
Python字節碼不是機器的二進制代碼,只是一種中間表示形式,所以python無法運行的和C/C++一樣快。
Python語言有三種主要的實現方式:CPython、Jython和IronPython。
Python是動態類型的(自動跟蹤你的類型而不是要求聲明的代碼),但也是強類型的(只能對一個對象進行有效的操作)
1 、十六進制和八進制表示 0XAF -> 175? , 010 ->8
2、math模塊 import math ,使用的時候math.sqrt(100),當確定自己不會導入多個同名函數的情況下,可以使用from math import sqrt ,以后就可以隨時使用sqrt函數了。
3、對于虛數的處理,使用cmath(complex math)模塊,這樣就可以對-1進行sqrt操作了。
4、input和raw_input的區別,input會假設用戶輸入的是合法的Python表達式,使用raw_input函數,它會把所有的輸入當做原始數據(raw data),然后將其放在字符串中。除非input有特別的需要,否則應該盡可能使用raw_input函數
5、在字符串前面加r,取消轉義
6、列表和元組的主要區別:列表可以修改而元組不能
7、列表的分片,列表[起始點,終止點之前一點,步長(默認為1)
8、字符串不能像列表一樣被修改,一般轉換為列表然后再進行處理
9、列表a、b,a=a+b的效率要低于a.extend(b),因為前者是在a+b后生成新的列表然后又賦值給a,而后者是在原a的基礎上擴展出b的
10、pop方法是唯一一個能夠修改列表又返回值的方法。lst.pop() 返回并刪除
11、tuple函數將列表轉化為元組 tuple([1,2,3])
12、模板字符串:string模塊提供一種格式化值的方法:模板字符串。它的工作方式類似于很多UnixShell里的變量替換。 from string import Template 。 具體google。
13、string模塊的join方法是split方法的逆方法。EG:seq = ['1','2','3','4','5'];sep = ',';s = sep.join(seq)
14、字符串的title方法,將字符串轉換為標題,也就是所有單詞的首字母大寫,而其他字母小寫。string = "that's all folks.";string.title()=="That'S All Folks."
15、strip方法返回去除兩側(不包括內部)空格的字符串。
16、使用dict的小Demo:
people = {
'Alice':{
'phone':1234,
'address':'beijing'
},
'Peter':{
'phone':4567,
'address':'shanghai'
},
'Micheal':{
'phone':9012,
'address':'hangzhou'
}
}
name = raw_input("please input the name : \n")
if(people.has_key(name)==False):
print "Not exist"
else:
profile = people[name]
#use dict to format the string
print "Phone is : %(phone)s \nAddress is : %(address)s" % profile
17、字典的拷貝,字典的普通copy方法是淺拷貝,只是簡單的拷貝值,但是如果涉及到應用的拷貝的話,就要考慮使用deepcopy方法進行深拷貝。
18、模塊的導入:
import somemodule
from somemodule import somefunction
from somemodule import somefunction, anthorfunction, yetanthorfunction
from somemodule import *
使用別名,避免沖突:import math as foobar
19、交換兩個值 x,y = y,x
20、== 測試相等性,即值是否相等,而 is 用于測試同一性,即是否指向同一個對象
21、a if b else c ; 如果b為真,則返回a,否則返回c
22、遍歷字典
d = {'x':1,'y':2,'z':3}
#Method1
for key in d:
print key ,'----->',d[key]
#Method2
for key in d.keys():
print key ,'----->',d[key]
#Method3
for (key , value) in d.items() :
print key , '----->' , value
23、zip函數可以用來進行并行迭代,可以將多個序列"壓縮"在一起,然后返回一個元組的列表
names = ['Peter','Rich','Tom']
ages = [20,23,22]
d = dict(zip(names,ages))
for (name,age) in zip(names,ages):
print name ,'----', age
print d['Peter']
24、在循環中添加else語句,只有在沒有調用break語句的時候執行。這樣可以方便編寫曾經需要flag標記的算法。
25、使用del時候,刪除的只是名稱,而不是列表本身值,事實上,在python中是沒有辦法刪除值的,系統會自動進行垃圾回收。
26、求斐波那契數列
def fibs(num):
'a function document'
result = [0,1]
for i in range(num-2):
result.append(result[-2]+result[-1])
return result
27、抽象函數(參數可以缺省,可以通過*p傳遞任意數量的參數,傳遞的是元組;通過**p傳遞任意數量的參數,傳遞的是字典)
def a(*p):
print p
def b(**p):
print p
a(1,2,3)
b(a='1',b='2',c='3')
"""
result:
(1, 2, 3)
{'a': '1', 'c': '3', 'b': '2'}
"""
28、使用globals()函數獲取全局變量值,該函數的近親是vars,它可以返回全局變量的字典(locals返回局部變量的字典)
29、隨機函數random.choice([1,2,3,4])
30、關于面向對象
#__metaclass__ = type
class Person:
#private variable
__name = ""
count = 0
def setname(self,name):
self.__name = name
def getname(self):
return self.__name
#private method using '__'
def __greet(self):
print "Say hello to %s !"%self.__name
def greet(self):
self.__greet()
def inc(self):
# ClassName.variableName means the variable belongs to the Class
# every instance shares the variable
Person.count+=1
#create instance
p = Person()
p.setname("Peter")
p.inc()
p2 = Person()
p2.setname("Marry")
p2.inc()
print "Name : " , p.getname()
#private method __Method is converted to public method _ClassName__Method
p._Person__greet()
print "Total count of person :? ", Person.count
p.count=12 # change the variable belong to the instance P
print p.count
print p2.count
31、python支持多重繼承,如果一個方法從多個超類繼承,那么必須要注意一下超類的順序(在class語句中):先繼承的類中方法會重寫后繼承的類中的方法,也就是后來將自動忽略同名的繼承。
32、使用hasattr(tc,'talk') 判斷對象tc時候包含talk屬性; 使用callable(getattr(tc,'talk',None)) 判斷對象tc的talk屬性是否可以調用,但是在python3.0之后,callable方法已經不再使用了,可以使用hasattr(x,'__call__')代替callable(x);使用setattr可以動態設置對象的屬性,setattr(tc,'talk',speek)
33、try:? except: else:??? finally:??? 可以捕捉多個異常,多個異常用元組進行列出,并且可以捕捉對象,
def test():
while True:
try:
x = raw_input("Please input the x: ")
y = raw_input("Please input the y: ")
print int(x)//int(y)
except ZeroDivisionError as e:
print "The second number can not be zero"
print e
else:
print "Nothing exception has happened!"
finally:
print "Clean up . It will be executed all the time"
34、異常和函數:在函數內引發異常時,它就會被傳播到函數調用的地方(對于方法也是一樣)
35、構造方法:def __init__(self , arguments)
36、子類不會自動調用父類的構造方法
37、查看模塊包含的內容可以使用dir函數,它會將對象(以及模塊的所有函數、類、變量等)的所有特性列出.__all__變量定義了模塊的共有接口(public interface)。更準確的說,它告訴解釋器:從模塊導入所有名字代表什么含義。eg: form copy import * 代碼你只能訪問__all__所定義的接口,而如果想訪問其他接口的話,就必須顯式地實現,from copy import PyStringMap
38、shelve模塊的簡單使用
'''
Created on 2011-12-11
A demo for shelve
@author: Peter
'''
import shelve
def store_person(db):
pid = raw_input("Enter the unique id for the person : ")
if pid in db :
print "The id exists , please change "
return
person = {}
person['name'] = raw_input("Enter the name of the person : ")
person['age'] = raw_input("Enter the age of the person : ")
person['phone'] = raw_input("Enter the phone number of the person : ")
db[pid] = person
def lookup_person(db):
pid = raw_input("Enter the id : ")
if pid not in db :
print "This is no that person"
return
field = raw_input("What would you like to know ? (name,age,phone) : ")
field = field.strip().lower()
print field.capitalize()+":"+db[pid][field]
def enter_command():
cmd = raw_input("Enter command : ")
cmd = cmd.strip().lower()
return cmd
def main():
database = shelve.open("database.bat")
try:
while True:
cmd = enter_command()
if cmd == 'store':
store_person(database)
elif cmd == 'lookup':
lookup_person(database)
elif cmd == 'exit':
return
finally:
database.close()
if __name__? == '__main__':main()
關于with和contextylib的用法:
平常Coding過程中,經常使用到的with場景是(打開文件進行文件處理,然后隱式地執行了文件句柄的關閉):
with file('test.py','r') as f :
print f.readline()
with的作用,類似try...finally...,提供一種上下文機制,要應用with語句的類,其內部必須提供兩個內置函數__enter__以及__exit__。前者在主體代碼執行前執行,后則在主體代碼執行后執行。as后面的變量,是在__enter__函數中返回的。通過下面這個代碼片段以及注釋說明,可以清晰明白__enter__與__exit__的用法:
#!encoding:utf-8
class echo :
def output(self) :
print 'hello world'
def __enter__(self):
print 'enter'
return self #返回自身實例,當然也可以返回任何希望返回的東西
def __exit__(self, exception_type, exception_value, exception_traceback):
#若發生異常,會在這里捕捉到,可以進行異常處理
print 'exit'
#如果改__exit__可以處理改異常則通過返回True告知該異常不必傳播,否則返回False
if exception_type == ValueError :
return True
else:
return False
with echo() as e:
e.output()
print 'do something inside'
print '-----------'
with echo() as e:
raise ValueError('value error')
print '-----------'
with echo() as e:
raise Exception('can not detect')
運行結果:
contextlib是為了加強with語句,提供上下文機制的模塊,它是通過Generator實現的。通過定義類以及寫__enter__和__exit__來進行上下文管理雖然不難,但是很繁瑣。contextlib中的contextmanager作為裝飾器來提供一種針對函數級別的上下文管理機制。常用框架如下:
from contextlib import contextmanager
@contextmanager
def make_context() :
print 'enter'
try :
yield {}
except RuntimeError, err :
print 'error' , err
finally :
print 'exit'
with make_context() as value :
print value
contextlib還有連個重要的東西,一個是nested,一個是closing,前者用于創建嵌套的上下文,后則用于幫你執行定義好的close函數。但是nested已經過時了,因為with已經可以通過多個上下文的直接嵌套了。下面是一個例子:
from contextlib import contextmanager
from contextlib import nested
from contextlib import closing
@contextmanager
def make_context(name) :
print 'enter', name
yield name
print 'exit', name
with nested(make_context('A'), make_context('B')) as (a, b) :
print a
print b
with make_context('A') as a, make_context('B') as b :
print a
print b
class Door(object) :
def open(self) :
print 'Door is opened'
def close(self) :
print 'Door is closed'
with closing(Door()) as door :
door.open()
運行結果:
總結
以上是生活随笔為你收集整理的python中start用法_Start Python 学习笔记(琐碎知识,持续更新。。。)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 围成一圈的排列组合问题_分班必考知识点!
- 下一篇: 电脑无法定位程序输入点于动态链接库怎么解