python10
面向对象的三大特征
封装
-
提高程序的安全性
-
将数据(属性)和行为(方法)包装到类对象中。在方法内部对属性进行操作,在类对象的外部调用方法。这样,无需关心方法内部的具体实现细节,从而隔离了复杂度。
-
在python中没有专门的修饰符用于属性的私有,如果该属性不希望在类对象内部访问,前边使用两个"_"
class Car:
def __init__(self,brand):
self.brand = brand
def start(self):
print('car is starting...')
car = Car('宝马')
car.start()
print(car.brand)
class Student:
def __init__(self,name,age):
self.name = name
self.__age = age # 年龄不希望在类的外部被使用,所以加了两个_
def show(self):
print(self.name, self.__age)
stu = Student('zhangsan',20)
stu.show()
# 在类的外部使用name,age
print(stu.name)
# print(stu.__age) # AttributeError
print(dir(stu))
print(stu._Student__age) # 在类的外部可以通过 _Student__age访问
继承
-
提高代码的复用性
-
如果一个类没有继承任何类,则默认继承object
-
python支持多继承
-
定义子类时,必须在其构造函数中调用父类的构造函数
class Person(object): # Person 继承 object类
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_nu):
super().__init__(name, age)
self.stu_nu = stu_nu
class Teacher(Person):
def __init__(self, name, age, teacher_age):
super().__init__(name, age)
self.teacher_age = teacher_age
stu = Student("zhangsan", 20,'1001')
teacher = Teacher("lisi", 34, 10)
stu.info()
teacher.info()
# 多继承 class A(object): pass class B(object): pass class C(A,B): pass
方法重写
-
如果子类对继承自父类的某个属性或方法不满意,可以再子类中对其(方法体)进行重新编写
-
子类重写后的方法通过super().xxx()调用父类中被重写的方法
class Person(object): # Person 继承 object类
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_nu):
super().__init__(name, age)
self.stu_nu = stu_nu
def info(self):
super().info()
print(self.stu_nu)
class Teacher(Person):
def __init__(self, name, age, teacher_age):
super().__init__(name, age)
self.teacher_age = teacher_age
def info(self):
super().info()
print(self.teacher_age)
stu = Student("zhangsan", 20,'1001')
teacher = Teacher("lisi", 34, 10)
stu.info()
teacher.info()
Object类
-
Object类是所有类的父类,因此所有类都是Object类的属性和方法。
-
内置函数dir()可以查看指定对象所有属性
-
Object有一个_ str _()方法,用于返回一个对于“对象的描述”,对应于内置函数str()经常用于print()方法,帮我们查看对象的信息,所以我们经常会对 __ str() __进行重写
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('zhangsan',20)
print(dir(stu))
print(stu) # 默认调用__str__()这样的方法
print(type(stu))
多态
-
提高程序的可扩展性和可维护性
-
简单的说,多态就是具有多种形态,它指的是:即便不知道一个变量所引用的对象到底是什么类型,动态决定调用哪个对象中的方法
class Animal(object):
def eat(self):
print('animal eat anything')
class Dog(Animal):
def eat(self):
print('dog eat meat')
class Cat(Animal):
def eat(self):
print('cat eat fish')
class Person(object):
def eat(self):
print('person eat good rice')
def fun(obj):
obj.eat()
# 开始调用函数
fun(Cat())
fun(Dog())
fun(Animal())
print('---')
fun(Person())
-
静态语言实现多态的三个必要条件
-
继承
-
方法重写
-
父类引用指向子类对象
-
特殊方法和属性
-
特殊属性
-
--dict--:获得类对象或实例对象所绑定的所有属性和方法的字典
-
class A:
pass
class B:
pass
class C(A,B):
def __init__(self, name):
self.name = name
class D(A):
pass
# 创建c类对象
x = C('jack') # x是c类的实例对象
print(x.__dict__) # 实例对象的属性字典
print(C.__dict__)
print('---------')
print(x.__class__) # <class '__main__.C'>输出对象所属类
print(C.__bases__) # c类的父类类型的元素
print(C.__base__) # 类的基类
print(C.__mro__) # 类的层次结构
print(A.__subclasses__()) # a的子类的列表
-
特殊方法
-
--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('zhangsan')
stu2 = Student('lisi')
s = stu1+stu2 # 实现了两个对象的加法运算,因为在Student类中,编写add特殊的方法
print(s)
s = stu1.__add__(stu2)
print(s)
print('------------------------')
lst = [11, 22, 33, 44]
print(len(lst)) # len 是内置函数len
print(lst.__len__())
print(len(stu1))
class Person(object):
def __new__(cls, *args, **kwargs):
print('__new__被调用执行了,cls的id值为i{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值为i{0}'.format(id(self)))
self.name = name
self.age = age
print('object这个类对象的id为:{0}'.format(id(object)))
print('Person这个类对象的id为{0}'.format(id(Person)))
# 创建Person类的实例对象
p1 = Person('zhangsan',20)
print('p1这个Person类的实例对象的id:{0}'.format(id(p1)))
类的浅拷贝与深拷贝
-
变量的赋值操作
-
只是形成两个变量,实际上还是指向同一个对象
-
-
浅拷贝
-
python拷贝一般都是浅拷贝,拷贝时,对象包含的子对象内容不拷贝,因此,原对象与拷贝对象会引用同一个子对象
-
-
深拷贝
-
使用cipy模块的deepcopy函数,递归拷贝对象中包含的子对象,原对象和拷贝对象所有的子对象也不相同
-
class CPU:
pass
class Disk:
pass
class Computer:
def __init__(self, cpu, disk):
self.cpu = cpu
self.disk = disk
# 变量的赋值
cpu1 = CPU()
cpu2 = cpu1
print(cpu1,id(cpu1))
print(cpu2,id(cpu2))
# 类有浅拷贝
print('---------------')
disk = Disk() # 创建一个硬盘类的对象
computer = Computer(cpu1,disk) # 创建一个计算机类的对象
# 浅拷贝
import copy
computer2 = copy.copy(computer)
print(computer,computer.cpu,computer.disk)
print(computer2,computer2.cpu,computer2.disk)
# 深拷贝
computer3 = copy.deepcopy(computer)
print(computer,computer.cpu,computer.disk)
print(computer3,computer3.cpu,computer3.disk)
模块
什么叫模块
-
模块英文为Modules
-
函数与模块的关系:一个模块中可以包含n多个函数
-
在python中一个扩展名为.py的文件就是一个模块
-
使用模块的好处
-
方便其他程序和脚本导入的使用
-
避免函数名和变量名冲突
-
提高代码的可维护性
-
提高代码的复用性
-
def fun():
pass
def fun2():
pass
class Student:
native_place = 'tianjing' # 类属性
def eat(self, name, age):
self.name = name
self.age = age
@classmethod
def cm(cls):
pass
@staticmethod
def sm():
pass
自定义模块
-
创建模块:新建一个.py文件,名称尽量不要使用与Python自带的标准模块名称相同
-
导入模块
-
import 模块名称 【as 别名】
import math # 关于数学运算 print(id(math)) print(type(math)) print(math) print(math.pi) print('------------') print(dir(math)) print(math.pow(2,3)) print(math.ceil(2)) print(math.floor(2.5))-
from 模块名称 import 函数/变量/类
import math # 关于数学运算 print(id(math)) print(type(math)) print(math) print(math.pi) print('------------') print(dir(math)) print(math.pow(2,3)) print(math.ceil(2)) print(math.floor(2.5)) -
def add(a,b):
return a+b
def div(a,b):
return a/b
# 如何导入自定义文件
# 在demo5中导入demo3自定义模块使用
import demo3
print(demo3.add(10,20))
print(demo3.div(10,2))
from demo3 import add
print(add(10,20))
以主程序形式运行
-
在每个模块的定义中都包括一个记录模块名称的变量—name—,程序可以检查该变量,以确定他们在哪个模块中执行。如果一个模块不是被导入到其它程序中执行,那么它可能在解释器的顶级模块中执行。顶级模块的—name——变量的值为-main_
def add(a,b):
return a+b
if __name__ == '__main__':
print(add(10,20)) # 只有当点击运行calc2时,才会执行
import calc2
print(calc2.add(100,200))
python中的包
-
包是一个分层次的目录结构,它将一组功能相近的模块组织在一个目录下
-
作用:
-
代码规范
-
避免模块名称冲突
-
-
包与目录的区别
-
包含_int _.py文件的目录称为包
-
目录里通常不包含_int _.py文件
-
-
包的导入 import 包名.模块名
python中常用的内置模块
-
sys:与python解释器及环境操作相关的标准库
-
time:提供与时间相关的各种函数的标准库
-
os:提供了访问操作系统服务功能的标准库
-
calendar:提供与日期相关的各种函数的标准库
-
urllib:用于读取来自网上(服务器)的数据标准库
-
json:用于使用JSON序列化和反序列化对象
-
re:用于在字符串中执行正则表达式匹配和替换
-
math:提供标准算数运算函数的标准库
-
decimal:用于进行精确控制运算精度、有效数位、和四舍五入操作的十进制运算
-
logging:提供了灵活的记录事件、错误、警告和调试信息等日志信息的功能
import sys
import time
import urllib.request
import math
import decimal
print(sys.getsizeof(24))
print(sys.getsizeof(45))
print(sys.getsizeof(True))
print(sys.getsizeof(False))
print(time.time())
print(time.localtime())
print(urllib.request.urlopen('http://www.baidu.com').read())
print(math.pi)
第三方模块的安装及使用
-
第三块模块的安装 pip install 模块名
-
第三方模块的使用 import 模块名










