1,python 是完全面向对象的语言。
在Python中一切都是对象,函数、模块、字符串等都是对象。
2,数据类型:数字,字符串,列表,元组,字典
数字型:整型、浮点型、布尔型(非零即真)、复数型
int(x),float(x).. 类型转换
非数字型:字符串、列表 []、元祖 () 、字典 {}
list(元祖) 元祖转列表
tuple(列表) 列表转元祖
比较运算符: ==,>=,!=,<=,>,<
逻辑运算符: and , or ,not,not in
身份运算符is ,比较两个对象的内存地址 是否一致, -- 是否是同一个对象的引用
针对None 比较时 , 推荐使用 is
变量 = 值一 if 条件 else 值二
三元运算: 1 if 5 - 3 > 2 else 3
切片
str[开始索引:结束索引:步长]
3,字符串
+ 拼接字符串
* 重复字符串
格式化输出:
%s 字符串
%d 整数 ,%06d 不到6位使用0占位
%f 浮点数 %.2f 显示2位小数
%% 输出%
name = "小明" age=23
print("我的名字是 %s ,年龄 %d,你好" % (name,age))
集合 set
集合:
不同元素组成
无序
集合中元素必须是不可变类型
s = {'hello', 'world', 'aa', 'bb', 'aa'}
print(s) #{'hello', 'aa', 'bb', 'world'}
x & y # 交集
x | y # 并集
x - y # 差集
4,类与函数
初始化方法 a,在内存分配空间–创建对象 b,为对象属性设置初始值 – 初始化方法(__init__自动调用)
del(self) 方法:销毁方法
str(self) 方法:类似toString()
class 类名(继承类):
count = 0
def __init__(self):
#给属性赋值None
self.name = None
@classmethod
def 类方法名(cls):
pass
# 静态方法
@staticmethod
def 静态方法():
pass
#伪私有属性和方法,在属性前加__
def __secret(self):
pass
#为对象在内存分配空间,返回对象引用
#单例模式 return super().__new__(cls)
__new__(cls, *args, **kwargs):
return
# 接口类定义
import abc
class Zoo(metaclass=abc.ABCMeta):
@abc.abstractmethod
def sleep(self):
"""子类必须实现"""
pass
定义函数
def 函数名():
return a, b
缺省参数,需放在末尾
def 函数名(sex=True):
内容
多值参数,参数前加*接收元组,加**接收字典
当参数不确定时使用
def 函数名(*args, **kwargs):
内容
dir(函数名) 查看函数内置
迭代器
1,迭代器协议:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么抛出一个StopIteration异常
2,可迭代对象:实现原理--》对象内部定义一个__iter()__方法
生成器
#自定义生成器函数
def test():
yield 1
yield 2
t = test()
print(next(t))
装饰器
#定义test的装饰器
def test_decorate(func):
def decorate(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
stop_time = time.time()
print("函数运行时间 %s" % (stop_time - start_time))
return res
return decorate
#@test_decorate 相当于调用 test = test_decorate(test)
@test_decorate
def test(name, age):
time.sleep(1)
print("我是 %s ,我的年龄 %d" %(name, age))
return "test"
result = test('xiaoming', 12)
print(result)
5,导入模块
import keyword 导入一个工具包
import random as rd
from 模块名 import 工具名
keyword.__file__ 查看模块完整路劲
__name__ == "__main__" 在当前模块执行成立
添加环境变量
import sys,os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_DIR)
6,文件操作
open 打开文件,并返回文件操作对象
第二个参数 r:只读 w:写覆盖 a:写追加
read 将文件内容读取到内存
readline() 一次读取一行
write将指定内容写入到文件
close关闭文件
os 文件操作模块,
python3 文件默认是UTF-8编码格式
eval() 把传入的字符串当表达式运算,
7,异常
try:
捕获代码
except Exception as result:
异常信息
else:
在没有异常时执行
finally:
...
主动抛出异常 raise Exception("...")
自定义异常
class MyException(BaseException):
def __init__(self, msg):
self.msg = msg
print(MyException("自定义异常"))
8,发布
创建setup.py
构建模块python3 setup.py build
生成发布压缩包python3 setup.py sdist
pygame 模块,专为电子游戏设计
pip3安装模块
pip3 install pygame