python雜記


一種設(shè)定全局參數(shù)的方法
import argparse

之后def個 get param的函數(shù) 或者不定義函數(shù)也行
def get_param():
parser = argparse.ArgumentParser(description='help info') #這里應(yīng)該隨便寫
parser.add_argument('--lr',default=0.1,type=float)
parser.add_argument('--num_epochs',default=5,type=int)
parser.add_argument('--batch_size',default=512,type=int)
args = parser.parse_args()
之后調(diào)用的時候就
args = get_param()
lr = args.lr
num_epochs = args.num_epochs
batch_size = args.batch_size


python class類

首先注意 定義class 時 定義的名字 首字母大寫 不帶括號 但帶冒號
但凡def的時候 括號內(nèi)第一個寫self
可以(也可以不def init
def init(self,a,b,c):
self.a = ..
self.b = ..
self.c = ..
聯(lián)想到做算法題時 會用到這個 就是a b c參數(shù)可以在下面的程序中用到


python 變量四種作用域 以及 global 關(guān)鍵字

L : local 局部作用域
舉例:

def f():
    x = 2
    return x  
x屬于L

E : enclosing 嵌套的父級函數(shù)的 局部作用域
舉例:

def f1():
    x = 5
    def f2():
        print(x)
    return f2  
x屬于E 可以理解為x不僅作用于f2 還作用于f2之上的f1 范圍更大一點

G : global 全局變量 就是模塊級別定義的變量
舉例:

x = 22
def f():
    x = 2
    return x 
print(x) > 22 : x屬于G 即全局的變量 不在函數(shù)的內(nèi)部

B : built-in 系統(tǒng)固定模塊里面的變量
B在程序中 很少見 也管不了
四者的執(zhí)行順序是 L E G B 即由內(nèi)而外

為什么需要global關(guān)鍵字:
看以下的程序:

x = 5
def add():
    x = x + 1
    return x

這樣執(zhí)行肯定報錯 因為函數(shù)中的x沒有定義
所以

x = 5
def add():
    global x 
    x = x + 1
    return x

這樣就能正常運行
不過話說 上面的那個例子 括號里傳遞 x 參數(shù)就解決了。。
這個global只能用在函數(shù)中啊
像是 下面這種運行會出錯。。

x = 5
global x 
def add():
    x = x + 1
    return x

if name == 'main'

https://www.zhihu.com/search?type=content&q=python%20name%20main
我理解的是 不會出大問題 別人不會跑不通
因為有些情況 自己寫的一份python會作為一個模塊 在其他py文件中進行調(diào)用
假如我寫了一份文件 qkx.py

如果不帶 if name main 的話 
import qkx  此時__name__的值是qkx   print(__name__) > qkx
如果不帶 if name main 的話 
import qkx  此時__name__的值還是__main__  print(__name__) > __main__

__name__這個東西暫且不管 貌似python中一直存在  且可以打印出來 print(__name__)

python與mysql的交互

參考
https://zhuanlan.zhihu.com/p/84504148?utm_source=wechat_session&utm_medium=social&utm_oi=638746686156181504&utm_campaign=shareopn


使用logging模塊代替print

首先 logging模塊有5個level
分別是 debug info warn error critical

debug:查看程序運行的信息
info:查看程序是否如預(yù)料執(zhí)行的信息
warn:意料之外的,但不影響程序運行
error和critical:一些比較嚴重的問題

import logging 
logging.basicConfig(level=logging.DEBUG , format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S') 
注意 level參數(shù)調(diào)用時要大寫
logging.debug("Hello")

一個完整的例子

import logging;

def loggingDemo():
    logging.info("You should see this info both in log file and cmd window");
    logging.warning("You should see this warning both in log file and cmd window");
    logging.error("You should see this error both in log file and cmd window");
    logging.debug("You should ONLY see this debug in log file");
    return;
    
def initLogging(logFilename):
    logging.basicConfig(
                    level    = logging.DEBUG,
                    format   = 'LINE %(lineno)-4d  %(levelname)-8s %(message)s',
                    datefmt  = '%m-%d %H:%M',
                    filename = logFilename,
                    filemode = 'w');
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler();
    console.setLevel(logging.INFO);
    # set a format which is simpler for console use
    formatter = logging.Formatter('LINE %(lineno)-4d : %(levelname)-8s %(message)s');
    # tell the handler to use this format
    console.setFormatter(formatter);
    logging.getLogger('').addHandler(console);
 
if __name__=="__main__":
    logFilename = "qkx_logging_demo.log";
    initLogging(logFilename);
    loggingDemo();

python sys

sys.argv是獲取運行python文件的時候命令行參數(shù)
有 qkx.py 文件如下:

import sys
a = sys.argv[0]
print(a)

返回 qkx.py

若是

import sys 
a = sys.argv[1]
print(a)

之后 若是在 cmd中 運行 qkx.py boy ,則會返回boy

這一點有啥用呢。。
可以在命令行里直接給參數(shù),不需要打開腳本改,比較方便?

呃。還是不太明白實戰(zhàn)中的最大作用 遇到再說吧


ipynb 轉(zhuǎn) py

jupyter nbconvert --to python qkx.ipynb
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容