python教程
1991年發(fā)布第一個版本
設(shè)計定位:Python的設(shè)計哲學(xué)是“優(yōu)雅”、“明確”、“簡單”。
Python開發(fā)者的哲學(xué)是“用一種方法,最好是只有一種方法來做一件事。
語言分類:腳本語言,NONONO,Python的支持者較喜歡稱它為一種高級動態(tài)編程語言
Python 2.7將于2020年1月1日終止支持,請使用python3.x
執(zhí)行Python在執(zhí)行時,首先會將.py文件中的源代碼編譯成Python的byte code(字節(jié)碼),然后再由Python Virtual Machine(Python虛擬機(jī))來執(zhí)行這些編譯好的byte code。
基本數(shù)據(jù)類型
m_int = 100 # 整數(shù)
m_float = 1000.0 # 浮點數(shù),精度與系統(tǒng)相關(guān)
m_bytes = b'hello'
m_complex = 2+2.7j # 復(fù)數(shù)
m_bool = True # 邏輯值, 只有兩個值:真、假
m_str = "runoob" # 一個由字符組成的不可更改的有序串行
m_tuple = (4.0, 'string', True) #可以包含多種類型的不可改變的有序串行,元組
m_list = [100, 'hello', False] # 有序列表,可包含多種數(shù)據(jù)類型
m_dict = {'key1': 1.0, 3: False} # 一個可改變的由鍵值對, map
方法,函數(shù)
定義方法:def 方法名(參數(shù)列表)
def test_fun():
print('hello world')
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
有默認(rèn)參數(shù)的函數(shù)
def spam(a, b=42):
print(a, b)
spam(1) # Ok. a=1, b=42
spam(1, 2) # Ok. a=1, b=2
任意數(shù)量參數(shù)的函數(shù)
def avg(first, *rest):
return (first + sum(rest)) / (1 + len(rest))
#接受任意數(shù)量的位置參數(shù)和關(guān)鍵字參數(shù)
def anyargs(*args, **kwargs):
print(args) # A tuple
print(kwargs) # A dict
單個返回值
def test_add(a, b):
return a + b
#調(diào)用方法
def test_add(1, 2)
def test_add('hello', 'world')
多個返回值
test_move_point(x, y, z):
x += 1
y += 1
z += 1
return x, y, z
#調(diào)用函數(shù)
a, b, c = test_move_point(1, 2, 3)
返回函數(shù)
def lazy_sum(*args):
def temp_sum():
ax = 0
for n in args:
ax = ax + n
return ax
return temp_sum
#調(diào)用
f = lazy_sum(1, 2, 3, 4)
f()
匿名函數(shù):lambda關(guān)鍵字
add = lambda: x, y: x + y
add(1, 2)
add('hello', 'world')
def square_sum(x, y):
return lambda: x * x + y * y
裝飾器,不帶參數(shù)
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print 'call %s():' % func.__name__
return func(*args, **kw)
return wrapper
@log
def my_func():
print('test my func')
#等價于
myfunc = log(my_func)
帶參數(shù)的裝飾器
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print '%s %s():' % (text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
裝飾器,對象
class Log:
def __init__(self)
類和實例
定義類
class Student:
pass
class Student(object):
pass
創(chuàng)建實例
s = Student()
定義變量和訪問限制
class User:
__all_user_count = 0
def __init__(self):
self.name = 'Tom'
self.age = 18
self.__money = 100 # 私有變量
User.__all_user_count += 1
def get_money(self):
return self.__money
def set_money(self, m):
self.__money = m
# 私有方法
def __use_money(self):
self.__money -= 1
# 靜態(tài)方法
@staticmethod
def create_user():
return User()
繼承和多態(tài)
class Fruits:
def __init__(self):
self.name = 'fruits'
def say_hi(self):
print('i am fruits')
class Apple(Fruits):
def say_hi(self):
print('i am apple')
class Pear(Fruits):
def say_hi(self):
print('i am pear')
多重繼承
- 新式類多繼承搜索順序:廣度優(yōu)先
- 經(jīng)典類多繼承搜索順序:深度優(yōu)先
class P(object):
def fun_a(self):
print('function from P')
class A(P):
def __init__(self):
self.name = 'b'
def fun_a(self):
print('function from A')
class B(P):
def __init__(self):
self.name = 'b'
class C(B, A):
def __init__(self):
A.__init__(self)
B.__init__(self)
獲取對象信息
type() 獲取對象type
dir() 所有屬性和方法
isinstance() 判斷是否為某類型或某類型的子類
特殊方法
__init__() 初始化方法,構(gòu)造方法
__str__() 配合str(object)方法調(diào)用
__repr__() 配合repr(object)方法,返回一個可以用來表示對象的可打印字符串
__call__() 對象是否可調(diào)用
__len__() 配合len(object)方法調(diào)用
文件讀寫
try:
f = open('D:/test.txt', 'r')
f.write('hello world')
finally:
if f:
f.close()
with open('D:/ttt.txt', 'w') as f:
f.write('hello world 123')
異常處理
# try...except...else
try:
f = open('D:/test.txt', 'w')
f.write('hello sb')
f.close()
except IOError as e:
raise e
else:
print('write file ok')
# try...except...finally
try:
f = open('G:/test.txt', 'w')
f.write('hello error')
except IOError as e:
raise e
finally:
if f:
f.close()
線程
調(diào)用start_new_thread啟動線程
thread.start_new_thread(function, args, kwargs=None)
繼承threading.Thread實現(xiàn)run方法
import threading
class ThreadTask(threading.Thread):
def run(self):
print('i am from thread task')
t = ThreadTask()
t.start()