0. 類中的__init__(…)函數
該函數是其所在類的初始化函數(可理解爲該類的構造函數),負責第一時間初始化指定對象。
當一個對象被創建,Python首先創建一個空對象,然後爲那個新對象調用init方法。
特點
- 系統默認在構造該類時調用
- 可附帶參數(需附帶參數是,第一個參數默認爲self)
Class MyClass:
def __init__(self, name)
self.name = name
print('This is __init__(...) function.')
1. format
- 字符串格式化
用法:
- 它通過 {} 和 : 替代傳統 % 方式
- 參考鏈接
>>> '{}, {}'.format('Hello', 'World!')
# 輸出:
>>> Hello, World!
2. print
- 默認換行輸出
- 如果實現不換行輸出,需要在行尾加逗號,
3. open
大家知道IO操作並不是會百分百成功,open接口也不例外,操作過程中可能會遇到異常(如文件不存在、文件丟失等);一旦open過程中出現異常,那麼對文件後續的close操作將得不到執行;因此,我們需要對open進行異常處理。
fp = open('filename.txt','r')
try:
for line in fp.readlines():
print line
except:
print 'error'
finally:
file.close()
這樣的寫法有點累,所以出現了簡便的“with open”的方式,包含了以上的異常處理,但寫法上更簡便了;可謂短小精悍:
with open('filename.txt', 'r') as fp:
data = fp.read()
4. raw_input() 和 input()
- raw_input(): 把輸入都當做一個字符串來處理
- input(): 根據輸入來做類型轉換(輸入部分由raw_input()來實現)
input()的源碼
def input(prompt):
return eval(raw_input(prompt))
格式:
a = raw_input("有關輸入的描述"):