下载anaconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/?C=M&O=D
安装:https://blog.csdn.net/HowieXue/article/details/118442904
查看内置关键字:
import builtins
print(dir(builtins))
输出:print(*objects,sep='',end='\n',file=sys.stdout,flush=False)
with open("./abc.txt",'w') as f:
print(12345,file=f) #把12345直接写入abc.txt文件
print('hello','peter',sep='-and-',end="--end")
#hello-and-peter--end
for i in range(10):
print('.',end='',flush=True)
time.sleep(0.3)
输入:input([prompt])
name = input("input ur name:")
print(name,"nice to meet u",sep=',')
#返回的是字符串
str = input("input nums like 1,2,3").split(',')
int([x],base=10)
complex([real[,imag]])
print(r"http:\\google.com\n")
其中的"\" "\n"不进行转义print("%s,%d,%f" % ("str",123,1.23))
{name}.format(name=" ")
print(f"{name}")
list(d.keys())
, get(key,default=None), update([other])dic = {'a':123,'b':23,'c':56}
total = 0
#方式1
for k in dic: #默认遍历键
v = dic[k]
if type(v) in (int,float,bool,complex): #判断是否为数值类型
total += v #累加
print(total)
#方式2
for k,v in dic.items():
k,v
a = [1,2,3,4]
del a[0]
print(a) #[2,3,4]
a=99
时,内存先开辟空间存放99,然后定义变量名a来指定这个空间的内存地址. python中的赋值语句不复制对象,只是建立引用关联.all(iterable)
:如果iterable的所有元素全为真值或iterable为空则返回Trueany(iterable)
:任一元素为真则True, 若可迭代对象为空,则返回False如 any([False,None,0])
id(a)==id(b)
True值 if 条件 else False值
count = 0
while count<10:
count+=1
if(count>5):
break #若break执行则else语句不执行
pass
print(count)
else:
print('count>10')
for i in list
range(len(list))
enumerate(iterable,start=0)
: 将索引和元素组成一个元组,返回的是迭代器。注意用list迭代第二次会出来空列表。for _ in range(num)
list1 = [1,2,3,4]
new_list = list1.copy() #list1[:],list(list1)
for i in new_list:
list1.remove(i)
d = {'name':'Tony','age':28,'height':180}
for k in d:
print(d.pop(k))
print(d)
#一定要保证在迭代期间,字典和集合的size不变,不然则报错
new_d = d.copy()
#d.[:]不可以, d.keys()不可以视图同原字典改变, list(d)获取新的键列表
for k in new_d:
print(d.pop(k))
list1 = [i**2 for i in range(6) if i%2]
print(list1)
#全等于
list2 = []
for i in range(6):
if i%2: #当为奇数时
list2.append(i**2)
print(list2)
'''
[1, 9, 25]
[1, 9, 25]
'''
#嵌套列表
mat = [ [1,2,3,4],
[5,6,7,8],
[9,10,11,12] ]
print(mat)
#不利用推导式进行转置
res=[]
for index in range(len(mat[0])):
list1=[]
for i in mat:
list1.append(i[index])
res.append(list1)
print(res)
#利用推导式进行转置
#根据上面对比一下
res1 = [[i[index] for i in mat] for index in range(len(mat[0]))]
print(res1)
{k: v for 子句 其他多个for子句或if子句}
dic = {x:y for x in range(6) for y in range(7,9)}
print(dic)
'''
{0: 8, 1: 8, 2: 8, 3: 8, 4: 8, 5: 8}
'''
s = {i+j for x in range(4,0,-1) for y in range(4)}
print(s)
'''
{1, 2, 3, 4, 5, 6, 7}
'''
__doc__
属性和内置函数help([object])
打印查看def my_abs(x):
"""Return the absolute value of the argument."""
return x if x > 0 else -x
# 文档注释存放在 __doc__ 属性中
print(my_abs.__doc__)
print()
help(my_abs)
'''
Return the absolute value of the argument.
Help on function my_abs in module __main__:
my_abs(x)
Return the absolute value of the argument.
'''
->
类型 表达__annotations
属性中Callable[[函数参数], 返回类型]
def func(a: int, b: str, c: list, d: tuple, e: dict, f:
set) -> tuple:
return a, b, c, d, e, f
print(func(1, 2, 3, 4, 5, 6))
print(func(1, "2", [3], (4, ), {5: 5}, {6}))
print(func.__annotations__)
'''
(1, 2, 3, 4, 5, 6)
(1, '2', [3], (4,), {5: 5}, {6})
{'a': , 'b': , 'c': , 'd': , 'e': , 'f': , 'return': }
'''
#多种类型
def func(a: Union[str,list,set]):
pass
#函数参数
def my_sort(a: list, f: Callable[[int], int], c: bool):
return sorted(a, key=f, reverse=c)
print(my_sort([1, -3, 2], abs, True))
*args
:将参数打包成元组给函数体调用,没有值传给它,就是个空元组**kwargs
:将参数打包成字典给函数体调用,没有值传给它,就是个空字典/
和*
来限制参数的传递形式
/
为仅限位置参数,限制在它之前的形参必须以位置参数的形式传入,而不能用关键字参数*
为仅限关键字参数,限制在它之后的形参必须以关键字参数的形式传入def func(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
pass
func(1, 2, 3, kwd1=4, kwd2=5)
lambda [arg1 [, arg2, ... argN]] : expression
a,*b=(1,2,3) #a=1,b=[2,3]
在其中一个变量前面加星号,代表可以接收多个元素,并组成列表来赋值。注意不允许多个带星号的变量def func(a, b, c, d=None):
print(a, b, c, d)
# 在可迭代对象前面加一个星号(*),使其以位置参数的形式传入函数
tup = (1, 2, 3, 4)
dic = {'name': "Tom", 'age': 18, 'height': 188}
func(*tup) # 等效于 func(1, 2, 3, 4)
func(*dic) # 等效于 func('name', 'age', 'height')
# 在字典对象前面加双星(**),使其以关键字参数的形式传入函数
dic = {'a': "Tom", 'b': 18, 'c': 188, 'd': True}
func(**dic) # 等效于 func(a="Tom", b=18, c=188, d=True)
dict(**dic) # 等效于 dict(a="Tom", b=18, c=188, d=True)
#使用json传递值
import json
jsonData = """
{
"a": "Tom",
"b": 18,
"c": 188,
"d": "True"
}
"""
text = json.loads(jsonData)
func(**text)
dir([object])
返回object的属性、方法列表的字符串数组locals() globals()
返回 变量名 和 变量值 的字典eval(expression[, globals[, locals]])
,exec(object[, globals[, locals]])
obj = "print(abs(-3))"
exec(obj)
obj = """
a = -3
if a < 0:
print(-a)
else:
print(a)
"""
exec(obj)
def outer():
global a, b # 声明当前作用域的a,b为全局变量
a, b, c, d = 3, 4, 5, 6
print(a, b)
def inner():
global a, b # 声明当前作用域的a,b为全局变量
nonlocal c, d # 声明当前作用域的c,d为Enclosing变量
a, b, c, d = 7, 8, 9, 0
inner()
print(a, b)
print(c, d)
a, b = 1, 2
outer()
print(a, b)
filter(function, iterable)
: 将 iterable 中每个元素作为参数传递给函数,根据函数的返回结果进行判断 True 或 False,将判断为 True 的 iterable 中的元素构建新的迭代器并返回map(func,*iterables)
: 用 iterables 中的每个元素作为函数的参数来调用函数,以迭代器形式返回所有结果。当有多个 iterables 对象时,最短的 iterables 耗尽则函数停止reduce(function, iterable[, initial])
:在指定 initial 参数时,先把 initial 值和 iterable 的第一个元素作为参数调用函数,把这次函数的结果以及 iterable 的下一个元素又作为参数再调用函数,以此类推from functools import reduce
def add(m, n):
s = m + n
print(s)
return s # 如果改为 print(s) 会怎样?
# 过程:[(1+2)+3]+4 = 10
result = reduce(add, [1, 2, 3, 4])
print(result)
'''
3
6
10
10
'''
#多层装饰器
import time
def deco(func):
print("in wrapper1")
#闭包函数
def wrapper1(*args):
print("start wrapper1")
res = func(*args)
print("end wrapper1")
return res
print("out wrapper1")
return wrapper1
def timer(func):
print("in wrapper2")
def wrapper2(*args):
print("start wrapper2")
start_time = time.time()
res = func(*args)
end_time = time.time()
print("函数耗时:{}".format(end_time-start_time))
print("end wrapper2")
return res
print("out wrapper2")
return wrapper2
@deco
@timer
def add(*args):
print("start add")
time.sleep(2)
print("end add")
return sum(args)
print(add(3, 4, 5))
#add其实是变化的函数的主体,deco和timer定义了这个变化函数周围固定的上下文作用,
#比如画不同的圆、方块、其他图形,可能载入的上下文都一样,就这个绘制部分的函数不一样,则可以使用装饰器
in wrapper2
out wrapper2
in wrapper1
out wrapper1
start wrapper1
start wrapper2
start add
end add
函数耗时:2.0025978088378906
end wrapper2
end wrapper1
12
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
@property
def adult_age_p(self):
return 18
def adult_age(self):
return 18
@staticmethod
def adult_age_static(): #静态函数参数中不添加self
return 30
@classmethod
def adult_age_class(cls,param): #class函数中注意添加cls参数
return param
@property
def adult_flag(self):
return self.age >= self.adult_age_p
stu = Student("张三", 18)
print(stu.adult_age()) # 没有加@property, 必须使用正常的调用方法的形式, 在后面加()
print(stu.adult_age_p) # 加了@property, 用调用属性的形式来调用方法, 后面不需要加()
print(stu.adult_flag) # True
print(Student.adult_age_static())
#print(Student.adult_age()) 不是静态函数不可直接使用
print(Student.adult_age_class(29))
stu.age = 17 # 可以修改stu对象的age属性
# stu.adult_age_p = 19 # 报错:@property将方法装饰为只读属性, 不能修改
print(stu.adult_flag) # False
18
18
True
30
29
False
Python常用魔术方法
定义:类中的魔术方法是官方定义好的,以两个下划线开头且以两个下划线结尾来命名的方法。在特定情况下,它会被自动调用,不需要我们主动调用该方法。
#__init__和__call__区别
class test:
def __init__(self):
print('__init__')
def __call__(self):
print('__call__')
test()
a = test()
a()
'''
__init__
__init__
__call__
'''
class Ex:
def __getitem__(self, key):
print(f"__getitem__被调用, key: {key}")
print(["a", "b", "c"][key])
print({0: "零", 1: "壹", 2: "贰"}[key])
def __len__(self):
return 1234
e = Ex()
e[2]
print(len(e))
'''
__getitem__被调用, key: 2
c
贰
1234
'''
import datetime
s = 'hello'
d = datetime.datetime.now()
print(str(s))
print(repr(s))
print(str(d))
print(repr(d))
'''
hello
'hello'
2018-11-29 22:39:18.014587
datetime.datetime(2018, 11, 29, 22, 39, 18, 14587)
'''
open(file, mode='r', encoding=None)
__enter__
__exit__
,在结束 with 语句体后会自动close文件with open(r'./t01.txt', mode='w') as file:
file.write('hello world')
import json
info = {'name': 'Tom', 'age': 18, 1: 'one'}
print(type(info), info)
with open("info.json", mode="w") as f:
info_str = json.dumps(info) # 序列化
print(type(info_str), info_str)
f.write(info_str)
with open("info.json") as f:
content = f.read()
print(type(content), content)
res = json.loads(content) # 反序列化
print(type(res), res)
__name__
属性:
print('在该模块自身运行时会执行')
print('在该模块被导入时也会执行')
if __name__ == '__main__':
print('在if语句下的程序块仅在该模块自身运行时才执行')
else:
print('在else子句下的程序块在该模块自身运行时不会执行')
print('但是在被导入时, 会执行')