本人一直使用最基本的写法,感觉比别人差别太多,对常用库但是没有深入使用,因此记录一下规范:
循环
for i in list: pass
# 平常习惯写 for 有时候需要获取数组的索引值,但是i又只能是值,
# 只能在外面重新定义一个变量,非常的麻烦且不美观
# 希望以后用枚举
for i, ch in enumerate(arr):pass
注解
def add(x : int , y : int) -> int: # 这里表示的是对参数和返回值的注解,入参都为int类型,返回值需要返回一个int型
return x + y # 如果没有返回值会将 -> int 框起来报警告
print(add.__annotations__) # 函数的注解存储在函数的__anotations__属性中
# {'x':<class int>,'y':<class int>,'return':<class int>}
int 和 bin
int('2', 2) # 可能你用过int()但是可能你没有用过后面那个参数,这里表示的是,将字符串2转化为10进制
bin(2) # 将10进制转化为2进制表示 这里返回0b10,取值的时候可以从第二位开始取值
if 与 else
# 使用if返回bool
if redata == data:
return True
else:
return False
# 不如用
return redata == data
#=======================
# 当简单的条件赋值返回:
if a:
a = a + 1
else :
a = b
if b:
b += 1
else:
b = a
# =======================
# 不如用:
a = a+1 if a else b
b = b+1 if b else a
取出类里面的值getattr
class A:
a = 1
# 正常取值
A.a
# 有逼格的取值
getattr(A,'a')
in 和__contains__
# 正常判断
if 'a' in 'abc':
pass
# 有逼格写法
if 'abc'.__contains__('a'):
pass
=========================
继续写