第九天

"""
面向对象的编程

面向过程:让程序按部就班的完成某一个功能,考虑代码的复用性,使用大量的函数封装代码
以函数为单位

面向对象:根据需求,划分成若干个类, 每个类会创建很多对象,以对象和对象之间的交互来进行类与类之间的沟通
以对象为单位

"""
# 员工请假
# 面向过程
"""
员工请假----领导审批----人事记录
请假(员工,领导)
撤回(员工,领导)
审批(员工,领导)
记录(人事,员工)
弊端:
1. 只看方法,不清楚角色关系(由参数决定)
2. 员工不该审批,领导也不需要请假,由于参数传递错误,可能造成功能问题

"""

# 面向对象
# 不是先考虑怎么做,先考虑涉及到谁,再考虑角色下有什么方法
class Worker:
def 请假(self,经理):
pass
def 撤回(self,经理):
pass
class Manager:
def 审批(self,员工):
pass
def 驳回(self,员工):
pass
class HR:
def 记录(self,员工):
pass
w=Worker()
m=Manager()
hr=HR()
w.请假(m)
w.撤回(m)
m.审批(w)
m.驳回(w)
hr.记录(w)


# 总结:面向过程 打(武松,老虎)
# 面向对象 武松.打(老虎)

# 面向对象的三个特征:封装、继承、多态

一、封装
# 封装:信息的隐藏,为了调用者方便调用。
# 封装是隐藏实现的细节,只提供给外界调用的接口,当底层细节发生改变的时候,不会给外界调用造成影响
1. 成员私有化
# 成员:类属性、类方法、实例属性、实例方法、静态方法
# 变量的私有化:在类里面定义的变量,只能在当前类中(定义属性或者方法的类)访问,不能在类外部进行访问
# 在python 里,如果在定义属性名(方法名),使用__ 开头,并且不以__结尾,这种定义下的属性或者方法就是私有变量

# class Computer:
# def __init__(self):
# self.cpu="inter5cpu"
# self.__memory=1024
# c=Computer()
# print(c.cpu)
# print(c.__memory)

# 怎么在类的外部访问的私有变量?
# 定义实例方法,在实例方法中访问私有变量
class Computer:
def __init__(self):
self.cpu1="inter5.cpu"
self.__memory1=1024
def get_memory(self):
return self.__memory1
def set_memory(self,m):
self.__memory1=m

c=Computer()
print(c.cpu1)
c.cpu1="i7cpu"
# print(c.__memory)
print(c.get_memory())
c.set_memory(2048)
print(c.get_memory())

# 封装的意义:方便调用者,当computer里面的memory名字发生了改变,调用者不需要改变调用方式

# 私有变量原理,python其实对于设置的私有变量只是修改了存储的名字
# [_类名+私有成员的名字]
# print("_Computer__memory1",c.Computer__memory1)

2. property:在类外部访问私有变量简化形式。
# (1) property 函数 (2) 使用property装饰器
(1) property函数
class Computer:
def __init__(self):
self.cpu="inter5cpu"
self.__memory=1024
def get_memory(self):
return self.__memory
def set_memory(self,m):
self.__memory=m
def del_memory(self):
del self.__memory
# 在类中定义property函数,里面包含4个参数
"""
1:get方法,名字
2:set方法
3:del方法
4:doc说明文档
"""
memory=property(get_memory,set_memory,del_memory,"电脑的内存大小")

# c=Computer()
# c.set_memory(2048)
# c.get_memory
# print(c.memory)
# c.memory=2048
# print(c.memory)
# del c.memory
# help(Computer.memory)

(2) 使用property装饰器
class Computer:
def __init__(self):
self.cpu="inter5cpu"
self.__memory=1024
# memory 是对外界提供的名字
@property
def memory(self):
"说明文档"
return self.__memory
@memory.setter
def memory(self,m):
self.__memory=m
@memory.deleter
def memory(self):
del self.__memory

c=Computer()
c.set_memory(2048)
c.get_memory()
print(c.memory)
c.memory=2048
print(c.memory)
help(Computer.memory)
del c.memory

二、函数补充
1. 递归深度
# 反复调用函数时有次数规定的。默认的递归深度是1000
import sys
# sys.setrecursionlimit(5)
print(sys.setrecursionlimit())
def a(n):
if n>1:
print(n)
else:
a(n+1)
a(1)

2. 函数的说明文档
def fun():
"""fun函数的说明文档"""
help(fun)
print(fun.__doc__)

3. 函数的注释
a=1
a="str"
# 对于函数的参数,标注类型,可以在参数后面加:类型
# 对于函数的返回值,标注返回值类型,可以定义函数时,冒号前面加->类型
def fun2(a:int,b:int)->int:
pass
print(fun2.__annotations__)
















































原文地址:https://www.cnblogs.com/ztx695911088/p/9079540.html