python最佳实践指南_我Python 最佳实践指南

# 嵌套函数与闭包

# 文件读取与写入 "a" "w" "r"

# yield lambda 函数(即一种匿名函数)

# 面向对象编程 (属性与方法)

__init__(self, *arg) # 构造函数

__str__(self) #@override return str_name

static attribute # 定义在 __init__ 函数外 所有类实例共享

# 继承与多态

class son(Parent):

pass

# super().method_name # 调用父类方法

# 注释

# Pypi

# 调试 (vscode 大法好)

# 创建可执行文件 (pyinstaller)

# setup 文件 requirements 文件

# ansible???

# python fg (终端)

# / or //

# int float NoneType bool

# str 在 python 里是 immutable sequences of unicode codepoints

# bytes 在 python 里是 immutable sequences of bytes

# .encode() .decode()

# list 在 python 里是 mutable sequences of objects

# dict 在 python 里是 mutable mappings of keys to values

# Special attributes in Python are delimited by double underscores

"""__name__ gives us the means for our module to detect whether it has been runas a script or imported into another module or the REPL."""

print(__name__)

if __name__ == '__main__':

function()

# sys.argv[1]

# advanced command line argument parsing:

# Python Standard Library: argparse

# Many third-party options such as docopt

# docstrings 的使用方式

"""descriptionArgs:description# 可选Raises:IOError: ......Returns:description"""

# #! 符号

#!/use/bin/env python3

# 注意: Module code is executed exactly once, on first import 即上面的 print 函数只会执行一次

# value equality vs. identity (使用 is)

# 一个容易出错的地方

a = [1, 2]

def replace(f):

f = [4, 5]

replace(a) # 结果: a 的值还是 [1, 2] 这其实还是一种闭包 (closure)

# 即 Function arguments are passed by object-reference (使用 id() 可以验证)

# dir() 查看属性 __name__ __doc__

#################################################

# Static # Dynamic

#################################################

Strong # # Python

#################################################

Weak # # JavaScript

#################################################

解释上图:

# 1.In a dynamic type system object types are only resolved at runtime

# 2.In a strong type system there is no implicit(隐式)type conversion

# 作用域

Local Enclosing Global Built-in(LEGB)

# 一个容易出错的地方

count = 0

def show_count():

print("count = ", count)

def set_count(c):

global count # 不加这一行会出错

count = c

# Everything is an Object(一切皆对象)

# we follow patterns Not to kill complexity But to master it

# Special cases aren't special enough to break the rules

# Python Collections(str/list/dict/tuple/range/set)

# 1.tuple

heterogeneous(各种各样的) immutable sequence

("www", 123, True) # in or not in

# 2. string

homogeneous(同类的,同性质的) immutable sequence of Unicode codepoints(characters)

.split() .join()

.partition() # divide a string into three around a seperator:

# prefix, separator, suffix

# 3. range

arithmetic(算数,算法) progression of integers

# 4. List

heterogeneous mutable sequence

.index(item) # ValueError if not found

.insert(index, item)

.extend(list)

.reverse()

.sort() # reverse=True

# built-in function

sorted(list)

list(reversed(list))

# 5. Dict

{}

dict([(), ()])

dicr(a=b, c=d)

.copy()

.update()

.values() # 忽略 keys

.keys() # 同上

.items() # 同上

from pprint import pprint as pp # pretty print 美化作用

# 6. Set

unordered collection of unique, immutable objects

{1, 4, 67, 8999}

s = set([list])

.remove()

.discard()

.copy()

.union() # 并集

.intersection() # 交集

.difference() # 交集的补集

.symmetric_difference() # 补集

.issubset() # 子集

.issuperset() # 父集

.isdisjoint() # 不相交

# Handle Exception (觉得用不到哎 大部分时候)

Rasie/Handle/Unhandled exceptions/Exception objects

try:

except ValueError: # except (ValueError, TypeError) as e:

# str(e)

(finally)

return

# Indentation Error/ SyntaxError/ NameError

# Iterable Objects(可迭代对象)

# List/Set/Dict Comprehension(递推式构造列表)

iter() # 获得 iterator

next() # 获得当前元素

# generator 通关 yeild 生成

from itertools import islice, count

any()

zip()

# unittest(单元测试)

unittest

# debugging

pdb

# distribute your program

# in the face of ambiguity, refuse the temptation to guess(这句话很有道理)

# You can pass -m to your Python command to have it run a module as a script

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值