-
目录
-
派生类实操
-
面向对象特征之封装
-
-
面向对象特征之多态
-
面向对象之反射
-
-
派生类实操
1.将时间字典序列化成json格式,由于序列化数据类型的要求,时间类型不属于json格式序列化的数据类型:
json函数中参数cls = JSONEncoder(是个类)
类中影响数据类型的方法是def default(self, o)
用派生方法在原有方法上做数据类型转换
最后继续执行父类JSONEncoder的后续步骤完成时间类型序列化
import json
import datetime
timesheet = {'today_time': datetime.date.today(),
'today_breather': datetime.time(1, 30)
}
# 序列化的数据类型
# +-------------------+---------------+
# | Python | JSON |
# +===================+===============+
# | dict | object |
# +-------------------+---------------+
# | list, tuple | array |
# +-------------------+---------------+
# | str | string |
# +-------------------+---------------+
# | int, float | number |
# +-------------------+---------------+
# | True | true |
# +-------------------+---------------+
# | False | false |
# +-------------------+---------------+
# | None | null |
# +-------------------+---------------+
class MyJSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime.date):
return o.strftime('%Y_%m-%d')
elif isinstance(o, datetime.time):
return o.strftime('%H:%M:%S')
return super().default(0)
res = json.dumps(timesheet, cls=MyJSONEncoder)
print(res) # {"today_time": "2022_07-28", "today_breather": "01:30:00"}
-
面向对象之封装
1.封装:隐藏对象的属性和实现细节,仅对外提供公共访问方式
python中没有实际的限制,只不过是改了个名字之后可以获得,但这样就失去了隐藏的意义,所以需遵循规则,按照新的方法去获取数据或修改数据
1.1 格式:以__name格式表示该数据为隐藏数据
1.2 作用:将变化隔离 、便于使用、提高复用性、提高安全性
class School(): school = '华清大学' def __init__(self, name, age, gander): self.__name = name self.__age = age self.__gander = gander # 学生获得学校及个人信息 def student_info(self): print(''' 姓名:%s 年龄:%s 性别:%s ''' % (self.__name, self.__age, self.__gander)) def student_revise_info(self, name, age): self.__name = name self.__age = age stu = School('jason', 18, '男') stu.student_info() # jason stu.student_revise_info('kevin', 22) stu.student_info() # kevin
class Student(): school = '南芜大学' def __init__(self, mathematics, major): self.mathematics = mathematics self.major = major @property def total_score(self): return self.mathematics+self.major stu = Student(90, 50) res = stu.total_score() print(res) # 140 无@property stu = Student(90, 50) res = stu.total_score print(res) # 140
-
面向对象特征之多态:一种事物的多种体现形式
1.定义:定义新的子类、重写对应的父类方法、使用子类的方法直接处理,不调用父类的方法
2.作用 :增加了程序的灵活性、增加了程序可扩展性
class School: def major(self): print('摄影专业') class Student1(School): def major(self): print('排名第一') class Student2(School): def major(self): print('排名倒数第一') stu = School() stu1 = Student1() stu2 = Student2() stu.major() # 摄影专业 stu1.major() # 排名第一 stu2.major() # 排名倒数第一
3.鸭子类型
只要你长得像鸭子 走路像鸭子 说话像鸭子 那么你就是鸭子
-
面向对象之反射
1.反射:通过字符串来操作对象的数据或方法,存在关键字字符串、对象肯定是需要进行反射操作
2.反射方法
2.1 hasattr():判断对象是否含有某个字符串对应的属性
2.2 getattr():获取对象字符串对应的属性
2.3 setattr():根据字符串给对象设置属性
2.4 delattr():根据字符串给对象删除属性
class School:
school = '南芜大学'
name = 'jason'
def student(self):
print('摄影专业')
stu1 = School()
obj = getattr(stu1, 'school')
print(obj) # 南芜大学
obj = hasattr(stu1, 'school')
print(obj) # True
setattr(stu1, 'major', '摄影专业')
print(stu1.__dict__) # {'major': '摄影专业'}
setattr(stu1, 'rank', '排名第三')
print(stu1.__dict__) # {'major': '摄影专业'}
delattr(stu1, 'rank')
print(stu1.__dict__) # {'major': '摄影专业'}
3.案例:
class FtpServer: def serve_forever(self): while True: inp = input('input your cmd>>: ').strip() cmd, file = inp.split() if hasattr(self, cmd): # 根据用户输入的cmd,判断对象self有无对应的方法属性 func = getattr(self, cmd) # 根据字符串cmd,获取对象self对应的方法属性 func(file) def get(self, file): print('Downloading %s...' % file) def put(self, file): print('Uploading %s...' % file) obj = FtpServer() obj.serve_forever()
注:python:一切皆对象
只要你有数据 有功能 那么你就是对象
文件名 文件对象
模块名 模块对象
linux系统:一切皆文件
只要你能读数据 能写数据 那么你就是文件
posted on
浙公网安备 33010602011771号