继承 json和csv文件
1.继承 - 让子类直接拥有父类的属性和方法
子类 - 继承者
夫类 - 被继承者
夫类:父类拥有的东西,子类都有,但是子类除了有父类的东西以外还拥有一些额外特有的东西
人(父类) -> 学生(子类,分类)
class Person:
z =100
print('========Person的init方法=======')
def __init__(self):
self.name = '小明'
self.age = '18'
self.gender = '男'
def eat(self):
print('吃饭')
def sleep(self):
print('睡觉')
@staticmethod
def x():
print('摸鱼')
@classmethod
def y(cls):
print('划水')
# class Student:
# def __init__(self):
# self.name = '小明'
# self.age = '18'
# self.gender = '男'
#
# def eat(self):
# print('吃饭')
#
# def sleep(self):
# print('睡觉')
#
# def study(self):
# print('学习')
#
# 2.继承语法
'''
calss 类名(父类)
说明文档
类的内容
'''
class Student(Person):
pass
stu = Student()
print(stu.name,stu.age,stu.gender,Student.z)
stu.eat()
stu.sleep()
Student.x()
Student.y()
print(stu.z)
# 2.子类是可以继承父类所有的内容(包括:类属性,对象属性,对象方法,类方法,静态方法)
# 3.在子类中添加内容
'''
1)添加类属性和添加方法
直接在子类中定义新的类属性和新的方法
2)在子类中添加对象属性
需要在子类的__init__方法中通过super()去调用父类的__init__方法来继承父类的对象属性
'''
class Teacher(Person):
profession ='老师'
def __init__(self):
# 主动调用父类的__init__方法继承父类的对象属性
# supper() - 获取当前类的父类对象
super().__init__()
self.title= '副教授'
def attemd_class(self):
print('上课')
t1 = Teacher()
print(Teacher.profession,t1.name,t1.title)
t1.sleep()
t1.attemd_class()
# super的用法(了解)
'''
super() - 获取当前类的父类
super(类,对象) - 获取指定类的父类(后面的这个对象必须是前面的类的对象)
'''
#object - python所有类的基类
print('====================')
class A(object):
def __init__(self):
self.a = 10
class B(A):
def __init__(self):
self.b = 20
class C(B):
def __init__(self):
self.c = 30
class D(C):
def __init__(self):
# 调用当前类的父类__init__
# supper().__init__
# supper(D,self).__init__
super(C,self).__init__()
self.d = 40
dd = D()
print(dd.d)
print(dd.b)
class Person:
def __init__(self,name,age=18,gender='男'):
self.name = name
self.age = age
self.gender = gender
class Student(Person):
def __init__(self,study_id,name,age = 12,gender = '男'):
super().__init__(name,age,gender)
self.study_id = study_id
# 打印当前类的对象的时候就会自动调用这个方法,打印的是谁,self就是谁,打印的结果就是这个函数的返回值(必须是字符串)
def __repr__(self):
# return self.name
return str(self.__dict__)
stu1 = Student('stu0001','小花')
print(stu1)
2 .json数据
1.json的作用
json是一种通用的数据格式,主要用于不同编程语言之间进行有效的数据交流
xml是另外种通用的数据格式:json更小更快,xml更安全
2.json数据格式
json数据格式要求:1)有且只有一个数据 ;2)唯一1这个数据必须是json支持的数据类型的数据
json 支持的数据类型:
1)数字 - 包括整数小数,表示的时候直接写:28,2,34,-233,—23,233,34,3,3e5
2)字符串 - 双引号引起来的数据:“abc”.“123”,“tabcn123u4e00”
3)布尔值 - 只有True 和 Fasle
4)数组 - 相当于pythoon-的列表里像当于 = phthon
5)字典 - 相当于python中的字典(键必须是字符串{键1:值1…}
6)空值
3.pyhton数据和json数据之间的相互转换
python中json模块包含了:loads,dumps
from json import loads dumps
1)json转python
json ->python
数字 int , float
字符串 str(会将双引号变单引号)
布尔 true->True false - >False
空值 null->None
数组 list
字典 dict
loads(json格式字符串) - 将json数据钻换成对应的pathon数据
说明:json 格式的字符串 - 字符串内容是json数据的字符串(去掉字符串外面的引号后是一个合法的json数据)
from json import loads
result = loads('"abc"')
print(result)
result = loads('100')
print(result)
result = loads('true')
print(result)
result = loads('[100,"abc",true,null]')
print(result)
#练习: 基于data.json 文件提取所有新闻的标题
# 方法1:正则
from re import findall
json_data = open('./data.json',encoding='utf-8').read()
result = findall(r'(?s)"title":s*"(.+?)",',json_data)
print(result)
# 方法2:json解析
python_data = loads(json_data)
for x in python_data['newslist']:
print(x['title'])
2)python转json
python -> json
int float 数字
str 字符串(单引号会双引号)
bool True->true False - >false
None None -> null
list tuple 数组
dict 字典
dumps(python数据) - 将指定的python数据转换成对应的json格式的字符串
from json import dumps
dumps(100) # '100'
dumps('abc') # '"abc"'
dumps(True) # 'true'
result = dumps({'a':10,20:'张','b':[1.23,False,None]})
print(result)
result = dumps((10,'abc',True,None))
print(result)
3.csv文件读操作
import csv
1.创建reader获取文件内容
1) csv.reader(文件对象) - 返回一个迭代器,迭代器中的元素就是每一行内容对应的列表
2) csv.DictReader(文件对象) - 返回一个迭代器, 迭代器中元素就是每一行内容对应的字典(第一行数据是键)
import csv
data = list(csv.reader(open('./files/2018年北京积分落户数据.csv',encoding='utf-8',newline='')))
data2 = csv.DictReader(open('./files/2018年北京积分落户数据.csv',encoding='utf-8',newline=''))
#2.获取迭代器中的内容
# print(next(data))
# print(next(data))
# print(list(data))
#
# print(next(data2))
# 练习 : 计算积分平均分
s= 0
for x in data[1:len(data)]:
s+= float(x[-1])
print(f'{(s/len(data)-1):.2f}')
4.csv文件写操作
import csv
# 1. 以列表为单位写入数据
writer = csv.writer(open('./files/students.csv','a',encoding='utf-8',newline=''))
# 2) 写入数据
# 一次写一行数据
writer.writerow(['name','age','gender','tel','score'])
# 同时写多行数据
writer.writerows([
['小明',22,'女','123',92],
['小红',22,'女','121',91]
])
# 2.以字典为单位写入数据
# 1)创建writer:csv.DictWriter(文件对象,键对应的列表)
# writer=csv.DictWriter(open('./files/students.csv','w',encoding='utf-8',newline=''),['name','age','gender','tel','score'])
# 写入数据
# 写入头部数据(键字典的键直接写道第一行)
# writer.writeheader()
# 一次写一行数据
# writer.writerow({'name':'小明','age':18,'gender':'男','tel':'123','score':99})