Python 進階學習筆記
阿新 • • 發佈:2017-09-20
def 進階學習 學習 blog 私有屬性 屬性和方法 .get line person
把函數作為參數
import math def add(x, y, f): return f(x) + f(y) print add(9, 16, math.sqrt)
map(f, list) 函數
接收一個 f 和一個 list,並通過把函數 f 依次作用在 list 的每個元素上,得到一個新的 list 並返回。
def f(x): return x * x list = [1, 2, 3, 4] print map(f, list) # [1, 4, 9, 16]
reduce(f, list) 函數
def f(x, y):return x * y reduce(f, [1, 2, 3, 4]) # 1*2*3*4
filter(f, list) 函數
過濾不符合條件的元素,返回符合條件元素組成的新的 list
sorted(list) 排序函數
sorted(list, f) 自定義排序
導入模塊
import math from math import pow, sin, log
動態導入模塊
try: import json except ImportError: import simplejson as json
使用 __future__
Python的新版本會引入新的功能,但是,實際上這些功能在上一個老版本中就已經存在了。要“試用”某一新的特性,就可以通過導入__future__模塊的某些功能來實現。
from __future__ import unicode_literals
python 模塊管理工具
easy_install
pip
創建類
class Person(object): pass user = Person()
給類的實例添加屬性
user.name = ‘wangxi‘ user.age = 25
初始化實例屬性
classPerson(object): def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender user = Person(‘wangxi‘, 25, ‘male‘) # user.name ‘wangxi‘ # user.age 25 # user.gender ‘male‘
對象屬性的訪問限制(私有屬性)
class Car(object): def __init__(self, name, color, price): self.name = name self.color = color self.__price = price Tesla = Car(‘Tesla‘, ‘white‘, ‘$23000‘) Tesla.name # ‘Tesla‘ Tesla.color # ‘white‘ Tesla.price # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # AttributeError: ‘Car‘ object has no attribute ‘price‘
創建類屬性和方法
綁定在類上,每個實例各自擁有,互相獨立
class Human(object): address = ‘Earth‘ __name = ‘man‘ # 私有屬性,在類的實例中無法訪問到 def __init__(self, name): self.name = name def getName (self): # 類的方法第一個參數一定是 self return self.__name # 類的方法中可以訪問私有屬性 me = Human(‘wangxi‘) me.address # ‘Earth‘ me.getName() # self 不需要顯式的傳入
類屬性可以動態添加和修改 (所有的實例訪問類屬性都會改變)
Human.address = ‘China‘ me.address # ‘China‘
如果實例屬性和類屬性沖突,則優先查找實例屬性
me.address = ‘Hangzhou‘ me.address # Hangzhou Human.address # ‘Earth‘
繼承
class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender class Student(Person): def __init__(self, name, gender, score): super(Student, self).__init__(name, gender): self.score = score
多態
特殊方法
__str__
將類的實例轉變成 str
後面的感覺對於我有點超綱了,暫時就不寫下去了。。有空再回來繼續學
Python 進階學習筆記