Python中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())
'''
posted @ 2021-12-14 19:08  索匣  阅读(69)  评论(0编辑  收藏  举报