一、转义字符:
\n #转义换行符
\t #转义制表符
\r #转义回车
\b #转义退格
原字符:不希望字符串中的转义字符起作用,就使用原字符,就是在字符串之前加上r或R 注意,最后一个字符不能是一个反斜杠。
二、转换:
8bit(位) = 1byte(字节)
1024byte(字节) = 1kb(千字节)
1024kb(千字节) = 1Mb(兆)
1024Mb(兆) = 1Gb(吉)
1024Gb = 1Tb(太)
ASCLL表 表示128个符号
三、命名
查看保留字
import keyword
print(keyword.kylist)
标识符命名规则:
①字母,数字,下划线
②不能以数字开头
③不能是python中的保留字
④区分大小写
四、变量
name = "恐龙妹go"
print("标识",id(name))
print("类型",type(name))
print("值",name)
五、计算
取余:
一正一负时: 余数 = 被除数-除数*商(被除数/除数)
六、类的定义及其应用
class Student:
native_pace = "吉林"
#初始化方法
def __init__(self,name,age):
self.name = name #self.name称为实体属性,进行一个赋值的操作,讲局部的name的值赋给实体属性
self.age = age
#实例方法
def eat(self):
print("学生在吃饭")
#静态方法
@staticmethod
def method(): #()里面不能些self
print("我使用staticmethod进行修饰,所以我是静态方法")
#类方法
@calssmethod
def cm(cls): #()里面些cls
print("我是类方法,因为我使用了classmethod进行修饰")
#在类之外定义的称为函数,在类之内定义的称为方法
def drink():
print("喝水")
print("------------------类方法的使用-----------------------------")
Student.cm() #使用cm去调用类方法
print("------------------静态方法的使用---------------------------")
Student.method()
为类动态绑定属性和方法
class Students:
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print(self.name + "在吃饭")
stu1 = Students("张三",20)
stu2 = Students("李四",30)
print("---------------------为stu2动态绑定性别属性----------------------")
stu2.gender = "女"
print(stu1.name,stu1.age)
print(stu2.name,stu2.age,stu2.gender)
print("---------------------为stu动态绑定方法----------------------")
def show():
print("定义在类之外的,称函数")
stu1.show = show
stu1.show()
七、封装
## 当类种的属性不想被外部调用时:
class Student:
def __init__(self,name,age):
self.name = name
self.__age = age #年龄不希望在类的外部被使用,所以加了两个_
def show(self):
print(self.name,self.__age)
stu = Student("张三",20)
stu.show()
print(stu.name)
print(stu.age) #这行不会输出,会报错,因为__age之内在类中被调用
八、继承
class Person():
def __init__(self,name,age):
self.name = name
self.age = age
def info(self):
print(self.name,self.age)
class Student(Person):
def __init__(self,name,age,stu_no):
super().__init__(name,age)
self.stu_no = stu_no
class Teacher (Person):
def __init__(self,name,age,teachofyear):
super().__init__(name,age)
self.teachofyear = teachofyear
stu = Student("张三",20,"1001")
teacher = Teacher("李四",34,10)
stu.info()
teacher.info()
多继承
class c(a,b):
pass
九、方法重写(其实上面的继承和封装都可以一并看向这个代码,只是分步进行)
class Person():
def __init__(self,name,age):
self.name = name
self.age = age
def info(self):
print(self.name,self.age)
class Student(Person):
def __init__(self,name,age,stu_no):
super().__init__(name,age)
self.stu_no = stu_no
def info(self):
super(Student, self).info()
print(self.stu_no)
class Teacher (Person):
def __init__(self,name,age,teachofyear):
super().info()
super().__init__(name,age)
self.teachofyear = teachofyear
def info(self):
#super().info()
super(Teacher, self).info()
print("教龄",self.teachofyear)
stu = Student("张三",20,"1001")
teacher = Teacher("李四",34,10)
stu.info()
teacher.info()
十object类
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return "我的名字是{0},今年{1}岁".format(self.name,self.age)
stu = Student("张三",20)
print(dir(stu))
print(stu)
十一、多态
class Animal(object):
def eat(self):
print("动物会吃")
class Dog(Animal):
def eat(self):
print("狗吃骨头")
class Cat(Animal):
def eat(self):
print("猫吃鱼")
class Person:
def eat(self):
print("人吃五谷杂粮")
def fun(obj):
obj.eat()
fun(Cat())
fun(Dog())
fun(Animal())
fun(Person())
十二、特殊方法和特殊属性
特殊属性
①__dict__获取类对象或实例对象的所有属性和方法的字典
class A:
pass
class B:
pass
class C(A,B):
def __init__(self,name,age):
self.name = name
self.age = age
x = C("Jack",20)
print(x.__dict__) #实例对象的属性字典
print(C.__dict__) #类对象的属性字典
print("----------------------------")
print(x.__class__) #输出了对象所属的类型
print(C.__bases__) #C类的父类型的元素
print(C.__base__) #类的基类,与子类最近的父类
print(C.__mro__) #类的层次结构
print(C.__subclasses__()) #子类的列表
特殊方法
①__len__()通过重写__len__()方法,让内置函数len()的参数可以是自定义类型
②__add__()通过重写__add__方法,可使用自定义对象具有“+”功能
③__new__同于创建对象
④__init__()对创建的对象进行初始化
a = 20
b = 100
c = a+b
d = a.__add__(b)
print(c)
print(d)
class Student:
def __init__(self,name):
self.name = name
def __add__(self, other):
return self.name+other.name
def __len__(self):
return len(self.name)
stu1 = Student("张三")
stu2 = Student("李四")
s = stu1+stu2 #实现了两个对象的加法运算(因为在Student类中 编写__add__()特殊的方法)
print(s)
x = stu1.__add__(stu2)
print(x)
print("---------------------------------")
lst = [11,22,33,44]
print(len(lst))
print(lst.__len__())
print(len(stu1))
class Person(object):
def __new__(cls, *args, **kwargs):
print("__new__被调用执行了,cls的id值为{0}".format(id(cls)))
obj = super().__new__(cls)
print("创建的对象id为:{0}".format(id(obj)))
return obj
def __init__(self,name,age):
print("__init__被调用了,self的id值为:{0}" .format(id(self)))
self.name = name
self.age = age
print("object这个类对象的id为:{0}" .format(id(object)))
print("Person这个类对象id为:{0}".format(id(Person)))
p1 = Person("张三",20)
print("p1这个Person类的实例对象的id:{0}".format(id(p1)))
十三、类的浅拷贝和深拷贝
变量的赋值操作:
class Cpu:
pass
class Dick:
pass
class Computer:
def __init__(self,cpu,dick):
self.cpu = cpu
self.disk = disk
cpu1 = Cpu()
cpu2 = cpu1
print(cpu1)
print(cpu2)
浅拷贝:
python拷贝一般是浅拷贝,拷贝时,对象包含的子对象内容不拷贝,因此,源对象与拷贝对象会应用同一个子对象
class Cpu:
pass
class Dick:
pass
class Computer:
def __init__(self,cpu,dick):
self.cpu = cpu
self.disk = dick
cpu1 = Cpu()
cpu2 = cpu1
print(cpu1)
print(cpu2)
#类有浅拷贝
print("-----------------------------")
dick = Dick() #创建一个硬盘类对象
computer = Computer(cpu1,dick) #创建一个计算机类对象
#浅拷贝
import copy
print(dick)
computer2 = copy.copy(computer)
print(computer,computer.cpu,computer.disk)
print(computer2,computer2.cpu,computer2.disk)
深拷贝:
使用copy模块的deepcopy函数,递归拷贝对象中包含的子对象,源对象和拷贝对象也不相同
class Cpu:
pass
class Dick:
pass
class Computer:
def __init__(self,cpu,dick):
self.cpu = cpu
self.disk = dick
cpu1 = Cpu()
cpu2 = cpu1
print(cpu1)
print(cpu2)
#类有浅拷贝
print("-----------------------------")
dick = Dick() #创建一个硬盘类对象
computer = Computer(cpu1,dick) #创建一个计算机类对象
#浅拷贝
import copy
print(dick)
computer2 = copy.copy(computer)
print(computer,computer.cpu,computer.disk)
print(computer2,computer2.cpu,computer2.disk)
print("----------------------------------")
#深拷贝
computer3 = copy.deepcopy(computer)
print(computer,computer.cpu,computer.disk)
print(computer3,computer3.cpu,computer3.disk)
十四、导入函数
import
import ①xxx import xxx② #导入①中的②函数,方便下面使用
引用自己定义的类或函数:右击文件夹选中Mark Directory as 选中其中的Sourcer Root即可
以主程序运行:
if name = “main”:
十五、python中的包
python中的包
包是一个分层次的目录结构,它是将一组功能相近的模块组织在一个目录下
作用:
代码规范
避免模块名称冲突
包与目录的区别
包括__init__.py文件的目录称为包
目录里通常不包含__init__.py文件
包的导入
import 包名.模块名
#使用import方式导入时,只能跟包名或模块名
import pageage1
import calc
#使用过from.........import 可以导入包,模块,函数,变量
from pageage1 import module_A
from pageage1 module_A import a
python中常用的内置模块
sys 与python解释器及其环境操作相关的标准库
time 提供与时间相关的各种函数的标准库
os 提供了访问操作系统服务功能的标准库
calender 提供了与日期相关的各种函数的标准库
urllib 用于读取来自网上(服务器)的数据标准库
json 用于使用json序列化和反序列化对象
re 用于在字符串中执行正则表达式匹配和替换
math 提供标准算数运算函数的标准库
cecimal 用于进行精准控制运算精度、有效数位和四舍五入操作的十进制运算
logging 提供了灵活的记录事件、错误、警告和调试信息等日志信息的功能
文件读写原理
file = open (filename [,mode, encoding])
被创建的文件对象 创建文件对象的函数 要创建或打开的文件名称 打开模式默认为只读 默认文本文件中字符的编写格式为gbk
file = open("a.text","r")
print(file.readlines()) #读取文件中所有的内容生成一个列表
file.close()
#文件的写入
file = open("b.text","w")
file.write("python")
file.close()
#文件的追加
file = open("b.text","a)
file.write("python")
file.close()
src_file = open("logo.png","rb") #二进制只读
target_file = open("copylogo.png","wb") #二进制写入
target_file.write(src_file.read())
src_file.close()
target_file.close()
方法名 说明
read(size ) 从文件中读取size个字节或字符内容返回,若省略[size],则读取到文件末尾,即一次读取文件所有内容
readline() 从文件中读取一行内容
readlines() 把文本文件中每一行都作为独立的字符串对象,并将这些对象放入列表返回
write(str) 将字符串str内容写入文件
writelines(s_list) 将字符串列表s_list写入文本文件,不添加换行符
seek(offset,[,whence]) 把文件指针移动到新的位置,offset表示相对于whence的位置,offset:为正往结束方向移动,为负往开始方向移动
0:从文件头开始计算
1:从当前位置开始计算
2:从文件尾开始计算
tell() 返回文件指针的当前位置
flush() 把缓冲区的内容写入文件,但不关闭文件
close() 把缓冲区的内容写入文件,同时关闭文件,释放文件对象相关资源
file = open("a.text","r")
#print(file.read(2))
#print(file.readline())
print(file.readline())
file1 = open("c.text","a")
file1.write("hello")
lst = ["java","go","python"]
file1.write(lst)
file.close()
with语句(上下文管理器)
with语句可以自动管理上下文资源,不论什么原因跳出with都能确保文件正确的关闭,以此来到到释放资源的目的
import os
os.system("notepad.exe") #打开记事本
os.system("calc.exe") #打开计算器
#直接调用可执行文件
os.startfile("文件路径\\文件名如(qq.exe"))
os模块用于操作目录的相关函数
函数 说明
getcwd() 返回当前的工作目录
listdir() 返回指定路劲下的文件和目录信息
mkdir(path[,mode]) 创建目录
makedirs(path1/path2…[,mode]) 创建多级目录
redir(path) 删除目录
removedirs(path1/path2/…) 删除多级目录
chdir(path) 将path设置为当前工作目录
os.path模块操作目录相关函数
函数 说明
abspath(path) 用于获取文件或目录的绝对路径
exists(path) 用于判断文件或目录是否存在,如果存在返回True,否则返回False
join(path,name) 将目录与目录或者文件名拼接起来
splitext() 分离文件名和拓展名
basename(path) 从一个目录中提取文件名
dirname(path) 从一个路径中提取文件路径,不包括文件名
isdir(path) 用于判断是否为路径
import os.path
print(os.path.abspath("one.py"))
print(os.path.exists("one.py"),os.path.exists("bucunzai"))
print(os.path.join("P:\\PyCharm","one.py"))
print(os.path.split("P:\PyCharm\one.py")) #将目录与文件拆分
print(os.path.splitext("one.py ")) #拆分文件与目录名
print(os.path.basename("P:\PyCharm\one.py"))
print(os.path.dirname("P:\PyCharm\one.py"))
print(os.path.isdir("P:\PyCharm\one.py"))
练习:
列出指定目录下的所有py文件
import os
path = os.getcwd()
lst = os.listdir(path)
for filename in lst:
#endswith获取文件后缀
if filename.endswith(".py"):
print(filename)