AI 作为时代的主旋律,了解和学习是必须得
Python是AI的主要编程语言:Python是开发和实施AI算法的首选语言之一。许多重要的AI库和框架,如TensorFlow、PyTorch、scikit-learn等,都是用Python编写的。
丰富的AI库和工具:Python生态系统中有许多用于机器学习、深度学习、自然语言处理(NLP)等领域的优秀库和工具。这些库使你能够快速开发、训练和测试AI模型。
可移植性和跨平台性:Python是跨平台的编程语言,可以在不同操作系统上运行。这使得你可以在不同的环境中部署和运行AI应用程序。
#python
I:\Environment\python\
#pip
I:\Environment\python\Scripts\
关于包管理还会用到 python虚拟环境、conda 等不同计算。比如 llama2,通义千问 等ai模型,都用了 conda 作为包管理, 而创建不同的python虚拟环境也可以把不同项目的依赖隔离开。
pip install <包名>
cmdC:\Users\haogg>I: I:\>cd I:\Environment\python\Scripts\ I:\Environment\python\Scripts>pip install ipython Collecting ipython Downloading ipython-8.14.0-py3-none-any.whl (798 kB) ... Installing collected packages: wcwidth, pure-eval, pickleshare, executing, backcall, traitlets, six, pygments, prompt-toolkit, parso, decorator, colorama, matplotlib-inline, jedi, asttokens, stack-data, ipython Successfully installed asttokens-2.2.1 backcall-0.2.0 colorama-0.4.6 decorator-5.1.1 executing-1.2.0 ipython-8.14.0 jedi-0.19.0 matplotlib-inline-0.1.6 parso-0.8.3 pickleshare-0.7.5 prompt-toolkit-3.0.39 pure-eval-0.2.2 pygments-2.16.1 six-1.16.0 stack-data-0.6.2 traitlets-5.9.0 wcwidth-0.2.6 [notice] A new release of pip is available: 23.1.2 -> 23.2.1 [notice] To update, run: python.exe -m pip install --upgrade pip
pip uninstall <包名>
pip list
pip freeze
shellpip install <包名> -i <国内地址>
texthttps://pypi.tuna.tsinghua.edu.cn/simple
texthttps://mirrors.aliyun.com/pypi/simple/
texthttps://mirrors.163.com/pypi/simple/
texthttps://pypi.douban.com/simple/
texthttps://mirror.baidu.com/pypi/simple/
texthttps://pypi.mirrors.ustc.edu.cn/simple/
texthttps://mirrors.huaweicloud.com/repository/pypi/simple/
texthttps://mirrors.cloud.tencent.com/pypi/simple/
单行注释以 #
号开头
多行注释用 '''
前后包裹
python# 单行注释以 # 号开头
'''
这是多行注释
'''
格式: 变量名 = 变量值
pythonvariable = '这是变量'
print(variable)
python# number
# int
number1 = 1
# float
number2 = 1.1
# 复数 1 + 3j
number3 = complex(1, 3)
# boolean
bool1 = True
bool2 = False
# String
String1 = "string variable"
String2 = 'tes\'t\''
print(String2)
# list
list1 = [1, 2, 3]
# Tuple 元组
tuple1 = (1, 2, 3, 4)
# Dictionary 字典
dict1 = {'name': 'test1', 'age': '11'}
print(dict1)
# Set 集合
s = {1, 2, 3, 4}
print(type(s))
type(<变量>)
python# type() 查看变量类型
type1 = type(dict1)
print(type1)
print(type1 == type({}))
'''
输出:
<class 'dict'>
True
'''
命名规范和格式规范可以参考 pep8
函数 | 说明 |
---|---|
int(x) | 将x转换为一个整型 |
float(x) | 将x转换为一个浮点型 |
str(x) | 将x转换为一个字符串 |
bool(x) | 将x转换为一个布尔值 |
python符号 | 描述 | java符号 |
---|---|---|
+ | 加 | + |
- | 减 | - |
* | 乘 | * |
/ | 除 | / |
// | 取整 | - (类型转换) |
% | 取余 | % |
** | 指数 | Math.pow(a, b) |
() | 小括号 | () |
python# 等号赋值
a = 10
# 多个变量共同赋值
b = c = 20
# 多个变量分别赋值
d, e, f = 1, 'string', 1.1
运算同时赋值
a += b
等价于:
a = a + b
运算符 | 描述 |
---|---|
+= | 加法赋值运算符 |
-= | 减法赋值运算符 |
*= | 乘法赋值运算符 |
/= | 除法赋值运算符 |
//= | 取整赋值运算符 |
%= | 取模赋值运算符 |
**= | 幂赋值运算符 |
运算符 | 描述 |
---|---|
== | 等于 |
!= | 不等于 |
> | 大于 |
>= | 大于等于 |
< | 小于 |
<= | 小于等于 |
运算符 | 表达式 | 描述 | java表达式 |
---|---|---|---|
and | x and y | 与,只要有一个是 False 就为 False | x & y |
or | x or y | 或,只要有一个是 True 就为 True | x | y |
not | not x | 非,取反,如果为 True 则为 False | !x |
特殊用法:
shella < 10 and pring(’hello world‘)
格式化输出: print('xxx %d %s' % (1, 'a'))
input('提示:')
pythoni = input('输入:')
i2 = input('输入:')
print("类型:%s ,类型2:%s" % (type(i), type(i2)))
# 输出 ====
输入:1
输入:aaa
类型:<class 'str'> ,类型2:<class 'str'>
python# 1. if
if ${expression} :
code
# 2. if .. else
if ${expression} :
code1
else:
code2
# 3. if elif
if ${expression} :
code1
elif ${expression2} :
code2
else:
code3
例如:
pythonage = int(input("你的年龄"))
if age >= 18:
print("青少年")
else:
print("不是青少年")
if age >= 18:
print("我成年了")
elif age <= 30:
print("我是青少年")
else:
print("我不是青少年")
pythonfor 临时变量 in 列表:
code1
例如:
pythonfor i in '我是谁?':
print(i)
#=======输出
我
是
谁
?
python# 生成一个[起始值, 结束值)
range(起始值, 结束值, 步长)
例如:
pythonprint(type(range(1, 11,5)))
for i in range(1, 11, 1):
print(i)
#=======输出
<class 'range'>
1
2
3
4
5
6
7
8
9
10
pythoncnt = int(input("打印次数:"))
while cnt > 0:
cnt -= 1
print("打印!")
# =====================输出
打印次数:2
打印!
打印!
立刻跳出循环
跳过当次循环
pythons = 'China'
# len 获取字符串长度
print('len 获取字符串长度: %d' % len(s))
# find 获取字符串第一次的长度,不存在
print('find 存在时:%d' % s.find('i'))
print('find 不存在时:%d' % s.find('w'))
# startswith 是否以什么开头, endswith 是否以什么结尾
print('startswith 存在时:%s' % s.startswith('Chi'))
print('startswith 从指定位置开始:%s' % s.startswith('ina', 2))
print('startswith 从指定位置开始指定位置结束:%s' % s.startswith('hina', 1, 4))
print('startswith 从指定位置开始指定位置结束:%s' % s.startswith('hina', 1, 5))
# count 计算出现的次数
s2 = 'chinese'
print('count 计算出现的次数: %d' % s2.count('i'))
print('count 计算出现的次数: %d' % s2.count('e'))
# replace 替换字符串
# replace(原字符串, 新字符串, 替换次数)
print('replace 替换字符串: %s' % s2.replace('e', 'w', 1))
print('replace 替换字符串: %s' % s2.replace('e', 'w'))
# split 切割字符串
s3 = "1,2,3,4,5,6,7"
print('split 切割字符串:%s' % type(s3.split(',')))
print('split 切割字符串:%s' % s3.split(','))
print('split 切割字符串:%s' % s3.split(',', 2))
# upper lower 大小写互换
print(s)
print('upper lower 大小写互换: %s' % s.upper())
print('upper lower 大小写互换: %s' % s.lower())
# strip 去除开头和结尾空格,或者指定字符
s4 = ' i am Chinese, ha ha haaaa'
print("strip 去除开头和结尾空格,或者指定字符: %s" % s4.strip())
print("strip 去除开头和结尾空格,或者指定字符: %s" % s4.strip('a'))
# join 字符串拼接
print('join 字符串拼接: %s' % s3)
print('join 字符串拼接: %s' % 'a'.join(s3))
print('join 字符串拼接: %s' % 'ab'.join(s3))
#==============输出
len 获取字符串长度: 5
find 存在时:2
find 不存在时:-1
startswith 存在时:True
startswith 从指定位置开始:True
startswith 从指定位置开始指定位置结束:False
startswith 从指定位置开始指定位置结束:True
count 计算出现的次数: 1
count 计算出现的次数: 2
replace 替换字符串: chinwse
replace 替换字符串: chinwsw
split 切割字符串:<class 'list'>
split 切割字符串:['1', '2', '3', '4', '5', '6', '7']
split 切割字符串:['1', '2', '3,4,5,6,7']
China
upper lower 大小写互换: CHINA
upper lower 大小写互换: china
strip 去除开头和结尾空格,或者指定字符: i am Chinese, ha ha haaaa
strip 去除开头和结尾空格,或者指定字符: i am Chinese, ha ha h
join 字符串拼接: 1,2,3,4,5,6,7
join 字符串拼接: 1a,a2a,a3a,a4a,a5a,a6a,a7
join 字符串拼接: 1ab,ab2ab,ab3ab,ab4ab,ab5ab,ab6ab,ab7
pythonlist1 = [1, 2, 3, '4']
print(list1)
print(type(list1))
# 不同元素类型可以不一样
for temp in list1:
print("list的元素类型: %s" % type(temp))
# append 尾部拼接
list1.append('5')
print(list1)
# 指定位置插入
list1.insert(0, '0')
print(list1)
list1.insert(1, 'a')
print(list1)
# extend 拼接
list2 = ['a', 'b', 'c']
list3 = [1, 2, 3]
list2.extend(list3)
print(list2)
#==============输出
[1, 2, 3, '4']
<class 'list'>
list的元素类型: <class 'int'>
list的元素类型: <class 'int'>
list的元素类型: <class 'int'>
list的元素类型: <class 'str'>
[1, 2, 3, '4', '5']
['0', 1, 2, 3, '4', '5']
['0', 'a', 1, 2, 3, '4', '5']
['a', 'b', 'c', 1, 2, 3]
pythonlist4 = [1, 2, 3, 4]
list4[1] = 1
print(list4)
#==============输出
[1, 1, 3, 4]
pythonlist5 = ['a', 'b', 'c', 1, '2']
print('in 测试查找: %s' % (2 in list5))
print('in 测试查找: %s' % ('2' in list5))
print('not in 测试查找: %s' % (2 not in list5))
print('not in 测试查找: %s' % ('2' not in list5))
#==============输出
in 测试查找: False
in 测试查找: True
not in 测试查找: True
not in 测试查找: False
pythonlist6 = [1, 2, 3, 4, 5, 6, 8, 9, 8, 9, 8]
del list6[1]
print('del 根据下标删除元素测试:%s' % list6)
print('pop 删除最后一个元素并返回: %s' % list6.pop())
print('pop 删除最后一个元素并返回后: %s' % list6)
print('pop index 删除指定元素并返回: %s' % list6.pop(2))
print('pop 删除指定元素并返回后: %s' % list6)
print('remove 删除指定元素值:%s' % list6.remove(8))
print('remove 删除指定元素值后:%s' % list6)
# ===========输出
del 根据下标删除元素测试:[1, 3, 4, 5, 6, 8, 9, 8, 9, 8]
pop 删除最后一个元素并返回: 8
pop 删除最后一个元素并返回后: [1, 3, 4, 5, 6, 8, 9, 8, 9]
pop index 删除指定元素并返回: 4
pop 删除指定元素并返回后: [1, 3, 5, 6, 8, 9, 8, 9]
remove 删除指定元素值:None
remove 删除指定元素值后:[1, 3, 5, 6, 9, 8, 9]
元组与列表类似,不同之处在于
pythontuple1 = (1,)
tuple2 = (1)
print("类型1: %s, 类型2: %s" % (type(tuple1), type(tuple2)))
#============输出
类型1: <class 'tuple'>, 类型2: <class 'int'>
切片指截取对象一部分的操作,字符串、列表、元组 都支持切片操作
语法:
[起始 : 结束 : 步长]
shelllist1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print('只有起始:%s' % list1[1:])
print('只有起始和结尾:%s' % list1[1:8])
print('只有起始和步长:%s' % list1[1::2])
print('全:%s' % list1[1:8:2])
print('只有结束:%s' % list1[:8])
print('只有结束和步长:%s' % list1[:8:2])
print('只有步长:%s' % list1[::2])
print('只有起始超过下标:%s' % list1[len(list1)::])
print('只有结束超过下标:%s' % list1[:len(list1):])
print('只有步长超过下标:%s' % list1[::len(list1)])
print('起始为负数:%s' % list1[-2::])
print('起始为负数:%s' % list1[len(list1) - 2::])
print('结束为负数:%s' % list1[:-2:])
print('结束为负数:%s' % list1[:len(list1)-2:])
print('步长为负数:%s' % list1[::-1])
print('类型:%s' % type(list1[::]))
print('类型:%s' % type(list1[1:2:1]))
tuple2 = (1, 2, 3)
print('类型:%s' % type(tuple2[1:2:1]))
# =================== 输出
只有起始:[2, 3, 4, 5, 6, 7, 8, 9, 10]
只有起始和结尾:[2, 3, 4, 5, 6, 7, 8]
只有起始和步长:[2, 4, 6, 8, 10]
全:[2, 4, 6, 8]
只有结束:[1, 2, 3, 4, 5, 6, 7, 8]
只有结束和步长:[1, 3, 5, 7]
只有步长:[1, 3, 5, 7, 9]
只有起始超过下标:[]
只有结束超过下标:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
只有步长超过下标:[1]
起始为负数:[9, 10]
起始为负数:[9, 10]
结束为负数:[1, 2, 3, 4, 5, 6, 7, 8]
结束为负数:[1, 2, 3, 4, 5, 6, 7, 8]
步长为负数:[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
类型:<class 'list'>
类型:<class 'list'>
类型:<class 'tuple'>
get (key, [default value])
xxx[key]
get 获取不到返回 None
[] 获取不到,抛出异常
xxx['key'] = new value
xxx['new key'] = value
del xxx[key]
del xxx
clear()
del 删除指定 key,clear 清空所有 key, del 不指定 key 把整个对象都删除了
pythondict1 = {'age': 14, 'name': 'yui'}
# 查看
print('下标查看元素:%s' % dict1['age'])
print('get 查看元素: %s' % dict1.get('age'))
print('get 不设置默认值:%s' % dict1.get('sex'))
print('get 设置默认值:%s' % dict1.get('sex', '男'))
# 修改
dict1['age'] = 19
print('修改后: %s' % dict1)
# 新增
dict1['sex'] = '男'
print('新增后: %s' % dict1)
# 删除
del dict1['sex']
print('del 删除后: %s' % dict1)
dict1.clear()
print('clear 删除后: %s' % dict1)
del dict1
print('del 删除整个后: %s' % type(dict1))
# ==================== 输出
Traceback (most recent call last):
File "F:\Study\CodePython\base\1\simple.py", line 225, in <module>
print('del 删除整个后: %s' % type(dict1))
^^^^^
NameError: name 'dict1' is not defined. Did you mean: 'dict'?
下标查看元素:14
get 查看元素: 14
get 不设置默认值:None
get 设置默认值:男
修改后: {'age': 19, 'name': 'yui'}
新增后: {'age': 19, 'name': 'yui', 'sex': '男'}
del 删除后: {'age': 19, 'name': 'yui'}
clear 删除后: {}
pythondict2 = {'age': 14, 'name': 'yui'}
for key in dict2.keys():
print('key: %s' % key)
for value in dict2.values():
print('value: %s' % value)
for key, value in dict2.items():
print('key: %s, value: %s' % (key, value))
for items in dict2.items():
print(type(items))
print(items)
# ============== 输出
key: age
key: name
value: 14
value: yui
key: age, value: 14
key: name, value: yui
<class 'tuple'>
('age', 14)
<class 'tuple'>
('name', 'yui')
pythonset1 = {value1, value2。。。}
set2 = set()
集合运算
python交集 set1 & set2 并集 set1 | set2 差集 set1 - set2 异或 set1 ^ set2 检查一个集合是否是一个集合的子集 set1 <= set2 检查一个集合是否是一个集合的真子集 set1 < set2 检查一个集合是否是一个集合的超集 set1 >= set2 检查一个集合是否是一个集合的真超集 set1 > set2
pythondef function_name([...args]):
code
return <result>
pythondef my_sum(v1, v2):
return v1 + v2
def my_sum(v1, v2, v3):
return sum(sum(v1, v2), v3)
r1 = my_sum(1, 2)
print(r1)
#======================输出
Traceback (most recent call last):
File "F:\Study\CodePython\base\1\simple.py", line 252, in <module>
r1 = my_sum(1, 2)
^^^^^^^^^^^^
TypeError: my_sum() missing 1 required positional argument: 'v3'
pythondef my_sum(v1, v2):
return v1 + v2
print(my_sum(1, 2))
def my_sum(v1, v2, v3):
return v1 + v2 +v3
print(my_sum(1, 2, 3))
# =====================输出
3
6
pythondef my_sum(*args):
print(type(args))
result = 0
for temp in args:
result += temp
return result
print(my_sum(1, 2, 3))
print(my_sum(1, 2, 3, 4))
# =====================输出
<class 'tuple'>
6
<class 'tuple'>
10
pythondef my_sum(v1, v2=1):
return v1 + v2
print(my_sum(1))
print(my_sum(1, 2))
# =====================输出
2
3
python 多个返回
python
def double_result():
return 1, 'b'
r1, r2 = double_result()
print("r1: %s, r2: %s" % (r1, r2))
print(double_result())
print(type(double_result()))
# =====================输出
r1: 1, r2: b
(1, 'b')
<class 'tuple'>
pythondef display(class_name, student_name, teacher_name):
print("class name: %s, student name: %s, teacher name: %s" % (class_name, student_name, teacher_name))
display('测试1', '名字1', 't2')
display('t2', teacher_name='测试2', student_name='名字2')
# ===================输出
class name: 测试1, student name: 名字1, teacher name: t2
class name: t2, student name: 名字2, teacher name: 测试2
pythondef display(a, b, c):
print("a: %s, b: %s, c: %s" % (a, b, c))
tuple1 = (1, 2, 3)
display(*tuple1)
tuple2 = (1, 2, 3, 4, 5)
display(*tuple2[1:4:1])
#===================输出
a: 1, b: 2, c: 3
a: 2, b: 3, c: 4
pythonhelp(function)
pythondef function():
'''
文档说明
'''
return
冒号 + 类型
参数说明, -> + 类型
结果说明,提示作用,不起限制pythondef fn(args<:type>) -> int:
code
pythonglobal 变量 = 变量值
命名空间
本质是一个字典,专门用来存储变量的
通过:
pythonlocals()
pythondef display(a, b, c):
# print("a: %s, b: %s, c: %s" % (a, b, c))
print('local:%s' % locals())
print(locals())
display(1, 2, 3)
# =================输出
{'__name__': '__main__', '__doc__': '\n多行注释\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001195C185150>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'F:\\Study\\CodePython\\base\\1\\simple.py', '__cached__': None, 'display': <function display at 0x000001195C1304A0>}
local:{'a': 1, 'b': 2, 'c': 3}
lambda 参数列表 : 返回值
pythondef fn(lst, fnc):
new_list = []
for n in lst:
if fnc(n):
new_list.append(n)
return new_list
def over5(n):
return n > 5
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(fn(l, over5))
print(fn(l, lambda n: n % 2 == 0))
#=====================输出
[6, 7, 8, 9, 10]
[2, 4, 6, 8, 10]
pythonl = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(filter(lambda i: i % 2 == 0, l)))
l.sort(key=lambda t: -t)
print(l)
#=====================输出
[2, 4, 6, 8, 10]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
将函数作为返回值返回
pythondef fn(add):
a = add
def inner():
print('a : %d' % a)
return inner
r1 = fn(10)
r2 = fn(11)
r1()
r2()
#================== 输出
a : 10
a : 11
python
def add(a, b):
return a + b
def mul(a, b):
return a * b
def begin_end(func, *args, **kwargs):
def new_funtion(*in_args, **in_kwargs):
print('入参为:%s' % (list(in_args) + list(in_kwargs)))
result = func(*in_args, **in_kwargs)
print('结果为: %s' % result)
return result
return new_funtion(*args, **kwargs)
def begin_end2(func):
def new_funtion(*in_args, **in_kwargs):
print('入参为:%s' % (list(in_args) + list(in_kwargs)))
result = func(*in_args, **in_kwargs)
print('结果为: %s' % result)
return result
return new_funtion
begin_end(add, 1, 2)
begin_end(mul, 2, 2)
begin_end2(add)(3, 4)
fun = begin_end2(mul)
fun(3, 3)
@begin_end2
def div(a, b):
return a / b
div(10, 2)
#=====================输出
入参为:[1, 2]
结果为: 3
入参为:[2, 2]
结果为: 4
入参为:[3, 4]
结果为: 7
入参为:[3, 3]
结果为: 9
入参为:[10, 2]
结果为: 5.0
pythonclass 类名[(父类)]:
code
python对象变量 = 类名()
pythonisinstance(object, class)
pythontype(MyClass) # <class 'type'>
方法参数一定需要有形参 self, 它是对类的当前实例的引用
初始化方法
pythondef __init__(self[, args……]):
code
使用算下划线开头 __
命名的变量只能在类内部访问
__name
改为 _className__name
@property 修饰的方法可以直接当成属性调用, 一般用在 getter 上
@属性名.setter
继承:class ClassName(SupperName……)
类名.__bases__
获取当前类所有父类特殊方法:
__del__()
方法,会在对象被回收时调用__str__()
-> toString()__repr__
使用 repr函数时生效,指定对象再交互模式中输出的结果__lt__()
: < , 重写后使用 < 号生效,入参 other 表示和当前对象比较的对象__le__()
: <=__eq__()
: ==__ne__()
: !=__gt__()
: >__ge__()
: >=__bool__()
: 转换成 boolean 类型是调用,返回结果则为转换结果python
class Person:
# 通过 Person.count 访问,为静态变量
# 通过 Object.count 访问,如果对象本身存在该变量,则返回本身变量,否则返回 Person.count
# 公共属性
count = 0
# 初始化方法
def __init__(self, name, age) -> None:
"""
构造函数
:param name: 名字
:param age: 年龄
"""
super().__init__()
self.__name = name
self.__age = age
Person.count += 1
def intro(self) -> None:
print("我是: %s, 今年 %d 岁" % (self.__name, self.age))
@property
def age(self):
# 这里 __age 改成 age 会变成循环调用,报错
return self.__age
@age.setter
def age(self, age):
self.__age = age
print(type(Person))
print(type(type))
xiaomin = Person('小明', 11)
xiaomin.count = 10
xiaohong = Person('小红', 11)
print(xiaomin.count)
print(xiaohong.count)
print(Person.count)
print("隐藏的实质 %s" % xiaomin._Person__name)
print("@property %s" % xiaomin.age)
xiaomin.age = 13
print("@property %s" % xiaomin.age)
# ================== 输出
<class 'type'>
<class 'type'>
10
2
2
隐藏的实质 小明
@property 11
@property 13
继承
python
# 继承
class Phone:
def __init__(self):
self.__weight = None
def __int__(self, weight):
self.__weight = weight
@property
def weight(self) -> int:
return self.__weight
@weight.setter
def weight(self, weight) -> None:
self.__weight = weight
def run(self):
print('phone: %s' % self.weight)
class XiaoMi(Phone):
# 重写 run
def run(self):
print('XiaoMi: %s' % self.weight)
class IPhone(Phone):
def run(self):
print('IPhone: %s' % self.weight)
class IMi(IPhone, XiaoMi):
pass
class MiI(XiaoMi, IPhone):
pass
phone1 = IMi()
phone2 = MiI()
phone1.weight = 10
phone2.weight = 11
phone1.run()
phone2.run()
print('获取所有父类:%s' % list(type(phone1).__bases__))
# ======================= 输出
IPhone: 10
XiaoMi: 11
获取所有父类:[<class '__main__.IPhone'>, <class '__main__.XiaoMi'>]
.py
文件就是一个模块python# 这种方式需要通过 模块名|别名.filed 使用模块属性
import 模块名(文件名,不包含.py) [as 别名]
# 只引入部分代码
from 模块名 import 方法名|类名, ... as 别名,...
# 也是引入全部内容, 不建议使用,相当于代码都引入,容易被当前模块覆盖
from 模块名 import *
同一个模块引入多次,模块实例只会被运行一次
__name__
获取当前模块名字
__main__
添加了下划线的变量,只能在模块内部被使用
.py
文件, 包是一个文件夹__init__.py
文件python# 异常的捕获
try:
code1(可能出现错误代码)
except [异常类型, Exception 全部异常] [as 实例名]:
code2(异常时处理代码)
else:
code3(没出错时要执行的代码)
finally:
code4(无论如何都会执行)
python# 抛出异常
raise Exception("异常了")
# 自定义异常: 类继承 Exception
class MyError(Exception):
code
python# with... as... 自动资源管理
with open(file_name) as file_obj:
pass
pythonfile_name = 'simple2.py'
try:
with open(file_name, encoding='utf-8') as file:
chunk = 100
content = ''
while True:
temp = file.read(chunk)
if not temp:
break
content += temp
print(content)
except FileNotFoundError:
print(f'{file_name} 不存在')
pythonopen(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
'''
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'''
本文作者:Yui_HTT
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!