[Python] 觀念小記

可變、不可變

參數分為可變、不可變兩種型態,不可變的有int,float,string

ex: str = 'abc'  , str[1] = 'a' , str[1] = 'd' -> error 不可

原因: Python變數使用參照方式,不可變形態中都是單一參照,不能對單獨內容改變


自訂義函式

定義中可以設定default值,但有設定的需在未設定的後面

ex: def add(a , b=0) -> ok  ,  def add (a = 1 ,b) -> error



輟星運算式


* , **  對函式輸入執行拆解 *拆解list , ** 拆解dictionary

ex: def add(*arg) -> add(1,2,3)  -> 輸入arg 為list -> arg=[1,2,3]


閉包和裝飾器


Python中 函式可以利用函式為輸入,在函式內有函式 又稱為閉包
利用此特性建立裝飾器 @

閉包
ex:
  def add(num1):
    def add2(num2):
        return num1+num2 
    return add2


利用gen_power(2)(3) 分別當成輸入 num1 和 num2 ,輸出為5

可以看出來num1會傳遞至下一層def中

藉此方法修飾函式,製作成裝飾器

ex: 想製作一個通用的輸出decorator



def print_func(title):
 def decorator(func):
  def modified_func(*args,**kwards):
   result =func(*args,**kwards)
   print title , result
  return modified_func
 return decorator


@print_func(title='result:')
def add(*lst):
 return sum(lst)


執行

add(1,2,3)

輸出  result: 6

decorator的執行流程

print_func -> decorator -> modified_func(進入此層條件為有call add) ->func(*1)->print title , result

(*1)func(*arg,**kwards) = add(1,2,3)因為不確定被修飾函式的種類和數量,因此利用*,**去囊括

第一層為decorator 的 輸入參數,第二層為輸入function,第三層為輸入function的輸入變數






物件導向

Python中 所有東西都是物件導向

Class 和 Function中有什麼不同

1. 同樣性質的參數可以只引入一次

2. 同類別的行為或動作可定義在一個class中,不需要個別定義

好處:

1. Class 中的繼承,在子類別後的括號中加入父類別名稱

2. 可在子類別中覆寫父類別的資訊

ex:

     

 1.   Class ____ (Parent Class)


 2.  Class Child(Parent Class):
        __init__:
          ......  (覆寫初始化)




套件


檔案夾裡有__init__.py的檔案就能夠當成是一個套件
import後可以引用套件內的.py檔案中的定義


click 套件 


利用裝飾器的特性包裝成的套件,對於命令列的輸入方式做解析
Option的輸入可以是, Key = Value
或使用shlex.split方式整理指令再輸入



yield的使用

打破副程式必須每次都從頭執行的概念
不清除掉程式call stack,記憶程式執行位置。
舉例

     
def print_word():
 a=1
 b=2
 c =yield a
 yield c

generator = print_word()
print generator.next()
print generator.send(10)
 
執行結果:
    

1
10

可以接收資料也可以送出資料,使用Next()的時候會執行到下一個yiled
遇到return就整個結束,不會有next()


import , __import__


import 用於 直接引用 如 import sys

__import__ 用於程式中動態引用,需輸入名稱 如 __import__ ('sys')






留言

這個網誌中的熱門文章

[單晶片]-寫I2C通訊(MPU6050為範例)

[單晶片]NEO-6M-0001透過U-center設定簡介

[研發替代役]-威聯通QNAP面試