1. 程式人生 > 其它 >20個常用的開發技巧

20個常用的開發技巧

巧妙的使用單下劃線

nums=(1,2,3,4,5,6,7,8,9)
head,*_,tail=nums # *_ 可代表中間那堆東西麼
print (head)
print (tail)

類的屬性封裝

class Person():
 pass
person=Person()
# 如果你有一個字典需要來初始化這個類;想得到能 print (person.first)
person_info={'first':'leo','last':'sam'}
# 用 setattr 函式
for k,v in person_info.items():
 setattr(person,k,v)
# 還有 getattr(),可以方便的獲取類的屬性
for k in person_info.keys():
 print (getattr(person,k)) # leo sam
# .輸入加密的密碼
from getpass import getpass
# username=input('Username: ')
# passwd=getpass('Passwd:') # getpass
# print ('Logging In...')

程式獲得當前檔案路徑

print(__file__)

9、獲得當前目錄

import os

print(os.path.abspath("."))

10、訪問 windows api;也沒看懂,反正跳出個tkinter差不多的模組

# (注:Windows 三大模組 GDI32.DLL 和 USER32.DLL 和 KERNEL32.DLL)
# import ctypes
# MessageBox = ctypes.windll.user32.MessageBoxA
# MessageBox(None, 'text', 'title', 0)

11、改變控制檯顏色

windows;反正vscode效果是控制檯輸出文字變紅
注:方法僅在 cmd 中有效,在 idle 中是無效的。

import ctypes
GetStdHandle = ctypes.windll.kernel32.GetStdHandle
SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
SetConsoleTextAttribute(GetStdHandle(-11), 0x04)

(2) posix(protable operating system interface of unix)

import sys
sys.stderr.write('\033[31m')
sys.stderr.write('\033[33m')
sys.stderr.write('\033[0m')

利用__class__訪問類的初始化定義變數

在 python 的建構函式中,無法通過變數定義直接訪問類中在建構函式外預定義
的變數,需要使用__clsss__關鍵字(其實直接用self也可以)

# 為什麼要在類建構函式中訪問建構函式外的變數呢,建構函式不是可以外部例項化時候傳參進來麼
# 怪不得要用建構函式傳參,類中的類屬性無法在函式中使用,在一般函式中加self即可,但為啥還需slef.__class__呢
class c1(object) :
    a=1
    def __init__(self):
        print(self.a) # 1
        print(self.__class__.a) # 這裡不能直接 print(a)
    def test(self):
        # print(a) # NameError: name 'a' is not defined
        print(self.__class__.a) 
c1().test() # 1

定義類的靜態函式;反正靜態函式就是不用類例項化就可以用類名呼叫,不用加括號()

class c1(object) :
    @staticmethod # 這是關鍵
    def printit1(txt) :
        print(txt)
    def printit2(txt) :
        print(txt)
c1.printit1("hello static method")
c1.printit2("hello static method") # 這樣是要報錯的;然並軟,並沒有報錯

定義類靜態變數

class c(object) :
    a = 1 # 不在__init__中定義的函式都是靜態變數
c1 = c() # python 的靜態變數對於每一個類例項都是有一個備份
c2 = c()
c1.a = 1
c2.a = 2
'''
1
2
1
'''
print(c1.a)
print(c2.a)
print(c.a)
c.a = 3 # 如果修改類靜態變數值之後建立的物件,的該值也會發生變化
c1 = c()
c2 = c()
'''
3
3
3
'''
print(c1.a)
print(c2.a)
print(c.a)

計數時使用 Counter 計數物件

from collections import Counter
c = Counter('hello world')
print(c) # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
print(c.most_common(2)) # [('l', 3), ('o', 2)]

漂亮的打印出 JSON

# 以使用indent引數來輸出漂亮的JSON。
# print(json.dumps(data, indent=2)) # With indention 縮排


### 建立一次性的、快速的小型 web 服務 
# 使用 SimpleXMLRPCServer 模組建立一個快速的小的檔案讀取伺服器的例子


### 互動環境下的 “_” 操作符
'''
這是一個我們大多數人不知道的有用特性,在 Python 控制檯,不論何時我們測
試一個表示式或者呼叫一個方法,結果都會分配給一個臨時變數: _(一個下劃
線)。
>>> 2+ 1
3
>>> _
3
'''

開啟檔案分享

'''
Python 允許執行一個 HTTP 伺服器來從根路徑共享檔案,下面是開啟伺服器的
命令:
# Python 2
python -m SimpleHTTPServer
# Python 3
python3 -m http.server
上面的命令會在預設埠也就是 8000 開啟一個伺服器,你可以將一個自定義的
埠號以最後一個引數的方式傳遞到上面的命令中
'''

重置遞迴限制

'''

Python 限制遞迴次數到 1000,我們可以重置這個值:
import sys
x=1001
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
'''
努力拼搏吧,不要害怕,不要去規劃,不要迷茫。但你一定要在路上一直的走下去,儘管可能停滯不前,但也要走。