Last active
October 9, 2017 12:10
-
-
Save 92hackers/81ee9f46f8dd5939d229d9903b18e1fa to your computer and use it in GitHub Desktop.
Important notes about Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# python built-in data types. | |
Boolean bool 值 True or Flase | |
String | |
Bytes / bytes array | |
Number | |
dict key/value pairs | |
tuple immutable unorder data | |
list ordered mutable data | |
set unorder mutable data, values is unique, | |
# import math. | |
math.floor(num) # 比num小的最大的一个数。 floor: 地板 | |
math.ceil(num) # 比 num 大的最小的一个数。 ceiling: 天花板。 | |
# 一个天上,一个地下。 | |
# list | |
list[:] # a good way to copy a list. | |
# list slice in python is so convient. | |
list[2: 6] # list slice is just the magic of __getItem__() | |
# 合并两个 list ? | |
# 添加元素进 list ? | |
# 删除一个元素, 根据 index, 根据 value ? | |
# Empty lists are false; all other lists are true. | |
# list, tuple index is negative when search from end, that means -1 is the last item. | |
# tuple immutable data type. | |
# list(a tuple) tuple(a list) list 跟 tuple 能够互转。 | |
# list destruct。 | |
# (dirname, filename) = os.path.split(pathname), 根据 位置,顺序,进行赋值。 | |
# empty tuple is False。 | |
# sets.add() sets.update() | |
# set 如何删除元素? | |
# set 如何新增元素? | |
# set 跟其他 set 比较,交集,补集,并集。 | |
# 在判断 True or False 的时候, empty set always False, others always True is it contains at least one item. | |
# Dictionary. | |
# 如何通过 value 找到 key? | |
# not {} == True : empty dict is False, others is True. | |
# How to swap key, value in a dict? | |
# a = {'name': 'cy', 'age': 24} | |
# {value: key for key, value in a.items()} 就能够颠倒了。 | |
# None is the only null value, a special constant in python. | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# get value with a key from a dict | |
cy.get('name', 'default value') # 如果 key 不存在,返回 default value, 不提供的话,返回 None | |
|| | |
|| | |
cy['name'] # 这个如果 name 不存在的话,会直接报错, | |
# 还有一种办法, __missing__(), 用来定义当没找到 key 的时候的返回值,默认值。 | |
# python 所有的功能都可以用 __missing__ , __str__ 这样的魔术方法来修改,因为所有东西都是面向对象的,各种功能都是调用那个 instance 的 相对应的 | |
# 魔术方法。 | |
# remove a key from dict | |
del cy['name'] # if name key do not exist, throw a key error. | |
cy.pop('name', 'default value') # if name key do not exist, return default value, no error throwed. | |
# 或者,加上 catch | |
try: | |
del cy['name'] | |
except KeyError as e: | |
print(e) | |
# python deep copy a dict. | |
import copy | |
a = {"name": [1,2,3,4]} | |
a_copy = copy.deepcopy(a) # 深拷贝,完全两份不同的内存空间。 | |
VS | |
a_copy = a.copy() # shallow copy, 虽然能把东西逗拷贝过来,其实里面的 collection 的内存地址还是一样的。可以用 id() 来验证。 | |
# 可以用 id() 来比较 两个变量是否指向同一个内存区域,这点是比较好的。 | |
# python3 conversion between byte and string. | |
a = 'hello, world' | |
a.encode() | |
# => b'hello, world' :bytes. | |
b = b'nice' | |
b.decode() | |
# => 'nice' : string. | |
# len(x) call x.__len__() | |
# __contains__(), is used by **in** operator | |
'a' in ['a', 'b'] | |
# => True | |
# iterate magic functions. | |
# iter() 调用 __iter__, 创造 iterator object, | |
# next() 调用 __next__, 取得下一个元素 | |
# essential in **for** loop: | |
for i in seq: | |
print(i) | |
# 首先调用 seq.__iter__()生成 iterator object, 然后调用 object.__next__(), 直到 iterate 完毕, | |
# for loop 相当于是自动帮你调用了那些方法。 | |
# 所有的 magic methods 想要自定义都需要在 class 里面自定义,因为所有东西都是对象,都是一个 class 来定义的。 | |
# How instalce get attribute ? 或者说:一个实例的属性怎么确定? | |
# 有两个方法可以用来控制获取属性: __getattr__, __getattribute__, | |
# __getattr__ : 如果 instance 本身没有定义属性的时候,就会到这个地方寻找。这个类似与定义默认的一些属性, | |
# __getattribute__ : 所有的获取属性,方法的操作都会经过这个方法,大总管。 | |
# __setattr__ : 用来设置属性。 | |
# 所以,尽可能只用 __getattribute__, 如果两个都存在的情况下,优先找 __getattribute__, 继承自 object 会自动的集成 __getattribute__ 方法, __setattr__方法。 | |
class test(object): | |
pass | |
# 函数调用: 调用 __call__(),这样的话,好灵活。函数的创建就太方便了。 | |
# 访问实例本身的一些属性,方法,这些都是自定义的,跟其他 class 不一样的, 魔术方法相当于将其中相同的部分抽离出来,也做成 方法, | |
# 只是这些魔术方法的调用不是直接通过方法名字来调用(虽说也可以,但是有更好的方法),而是通过一些公共的方法,比如: len(), str(), iter(), | |
# 或者是通过一些操作符,比如: 'a' in [], **in** 操作符, +, -, for ... in ...: 这样。 | |
# 还有比如获取 dict 的 items, __getitem__()。 items['key'] | |
# 数字操作: +, -, *, /, % 这些都抽象为了魔术方法,这样的好处是: + 加法这种操作符不只能用在数字之间,只要你在 class 里面定义了这个, | |
# 就能够用 + 加法运算符。 | |
# int(x) call x.__int__()。 | |
# 基本上所有的操作符, 全局操作函数都有对应的 **魔术方法**, 让你能够自定义各种行为,当在那种情况当中的时候。 | |
# 比如: 修改 __str__() 方法能够修改 str(xx) 或者字符串相加时候的默认行为。 | |
# with 构造的 context 本质也是调用 __enter__(), __exit__()。 | |
# 包括 class 的新建,实例化,都是调用 魔术方法,可以说,魔术方法构成了 python 的基石。因为它将所有的操作都封装成了对魔术方法的调用。 | |
# def x(*args, **kwargs): 这种用法的根本目的,是为了将无限个参数传递给函数,然后将他们全部包裹在 args, kwargs里面,是为了处理任意参数的问题。 | |
# d = [1,2,3,4] x(*d) => 这种目的是解包,这样就可以将我要传递的参数全部放在一个 list or dict 里面,不需要一个一个的写在括号里面。 | |
# lambda, anoymonus function, just single expression. | |
# lambda arguments: expression : lambda a: a + 10 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 密码必须是混合 字母 和 数字 的正则表达式。 | |
password_pattern = '^(?![a-zA-Z]{6,18}$)(?![0-9]{6,18}$)[a-zA-Z0-9]{6,18}$' | |
another = '^([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*$' | |
# 问题分析: 如果增加一个至少有一个大写的条件,就是三个组合。这样的话,将其拆分为三个小的是比较好的,然后手动加限制。 | |
# 问题分析: 数字 + 字母 + 数字, 字母 + 数字 + 字母, 字母 + 数字 / 数字 + 字母。 | |
# 下次必须仔细分析问题。 | |
# re模块 有两种使用方式, re.compile('[a-z]+') 构造 reg object, 然后 regobject 这个实例有很多方法可用, 或者是直接使用 re 的 | |
# 静态方法: re.match(), re.search()。 | |
# 还有一个 match_object 的概念,是匹配之后的结果,没有匹配到,就是 None, | |
# search() VS match() : match() 是从开头开始匹配, search() 是从任意位置。 | |
# differences between re.match() and re.fullmatch()? | |
# match just match from begining of text, but fullmatch() match from beginning to ending. all matched. | |
# re.sub(), subtitute, 类似 js 里面的 replace(), 替换 正则匹配到的文本,替换就是用这个方法,应该 python 里面所有跟正则表达式相关 | |
# 的方法都在这个里面,所以, str 里面没有直接处理正则的方法。 | |
# re.escape() : 用来 escape 正则的特殊字符: +, - \ / ., 如果你想要匹配这些特殊字符,就需要 re.escape() 你自己的正则表达式。 | |
# 正则表达式规则 + re.match() methods + regex object + match object | |
内容好多,果然经过多年的发展, python 已经相当的庞大了。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
我想要把这个 snippet 做成一个 python 的集锦。甚至可以多加一些另外的文件。