文章目录
【总结】继承、json数据与csv文件(2022.05.08)
1. 继承
1.1 继承概述
子类 - 继承者
父类 - 被继承者
关系:父类拥有的东西,子类都有,但是子类除了有父类的东西以外还有一些额外特有的东西。
1.2 继承语法
"""
class 类名(父类):
说明文档
类的内容
"""
# 人(父类) -> 学生(子类、分类)
class Person:
def __init__(self):
self.name = '小明'
self.age = 18
self.gender = '男'
def eat(self):
print('吃饭')
def sleep(self):
print('睡觉')
# 学生类继承上例人类
class Student(Person):
pass
stu = Student() # 创建对象
# 继承对象属性
print(stu.name, stu.age, stu.gender) # 小明 18 男
# 继承对象方法
stu.eat() # 吃饭
stu.sleep() # 睡觉
注意:子类是可以继承父类所有的内容(包括:类属性、对象属性、对象方法、类方法、静态方法)
1.3 在子类中添加内容
1)添加类属性和添加方法:直接在子类中定义新的类属性和新的方法
# 学生类继承上例人类
class Student(Person):
# 直接添加类属性
profession = '老师'
# 直接添加类方法
def attend_class(self):
print('上课')
2)添加对象属性:需要在子类的__init__
方法中通过super()去调用父类的__init__
方法来继承父类的对象属性
class Teacher(Person):
# 直接添加类属性
profession = '老师'
# 直接添加类方法
def attend_class(self):
print('上课')
# 添加对象属性
def __init__(self):
# 主动调用父类的__init__方法去继承父类的对象属性
# super() - 获取当前类的父类对象
super().__init__()
print('========Teacher中的init============')
self.title = '副教授'
1.4 super的用法
super() - 获取当前类的父类
super(类, 对象) - 获取指定类的父类(后面的这个对象必须是前面的类的对象)
# object - python所有类的基类
class A(object):
def __init__(self):
self.a = 10
# 创建B类继承A类
class B(A):
def __init__(self):
self.b = 20
# 创建C类继承B类
class C(B):
def __init__(self):
self.c = 30
# 创建D类继承C类
class D(C):
def __init__(self):
# 1.调用当前类的父类的__init__
# super().__init__()
# super(D, self).__init__()
super(C, self).__init__() # 继承C类的父类(不继承C类,继承B类)
self.d = 40
dd = D()
print(dd.d)
print(dd.c) # AttributeError: 'D' object has no attribute 'c'
print(dd.b)
1.5 __repr__
方法
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 f'学号:{self.study_id}, 姓名:{self.name}, 年龄:{self.age}, 性别:{self.gender}'
return str(self.__dict__)
stu1 = Student('stu001', '小花', gender='女')
print(stu1)
stu2 = Student('stu002', '小明')
print(stu2)
2. json数据
2.1 json的作用
1)json是一种通用的数据格式,主要用于不同编程语言之间进行有效的数据交流
2)xml是另外一种通用的数据格式;json更小更快;xml更安全
2.2 json数据格式
json数据格式的要求:
-
一个json有且只有一个数据;
-
唯一的这个数据必须是json支持的数据类型的数据
json支持的数据类型:
1)数字 - 包括整数和小数,表示的时候直接写:如28、2.34、-233、23.3、3e5
2)字符串 - 双引号引起来的数据(支持转义字符):如"abc"、“123”、“\tabc\n123\u4e00”
3)布尔 - 只有true和false
4)数组 - 相当于python的列表: [元素1, 元素2, 元素3,…]
5)字典 - 相对于python的字典(键必须是字符串):{键1:值1, 键2:值2,…}
6)空值 - null
2.3 python数据和json数据之间的相互转换
python中json模块包含了:loads、dumps
1)json转python
json | python |
---|---|
数字 | int、float |
字符串 | str(会将双引号变成单引号) |
布尔 | true -> True; false -> False |
空值 | null -> None |
数组 | list |
字典 | dict |
loads(json格式的字符串) - 将json数据转换成对应的python数据。
说明:json格式的字符串 - 字符串内容是json数据的字符串(去掉字符串外面的引号后是一个合法的json数据)
from json import loads, dumps
result = loads('"abc"') # 'abc'
print(result)
result = loads('100') # 100
print(result, type(result))
result = loads('true') # True
print(result)
result = loads('[100, "abc", true, null]')
print(result) # [100, 'abc', True, None]
# 练习:基于data.json文件,提取所有新闻的标题
json_data = open('data.json', encoding='utf-8').read()
# 方法一 - 使用正则
result = findall(r'(?s)"title":\s*"(.+?)",', json_data)
print(result)
# 方法二 - 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格式的字符串
dumps(100) # '100'
dumps('abc') # '"abc"'
dumps(True) # 'true'
result = dumps({'a': 10, 20: '余婷', 'b': [1.23, False, None]})
print(result) # '{"a": 10, "20": "余婷", "b": [1.23, false, null]}'
result = dumps((10, 'abc', True, None))
print(result) # '[10, "abc", true, null]'
3. csv文件
3.1 csv文件的读操作
- 创建reader获取文件内容
列表法:csv.reader(文件对象) - 返回一个迭代器,迭代器中元素就是每一行内容对应的列表
字典法:csv.DictReader(文件对象) - 返回一个迭代器,迭代器中元素就是每一行内容对应的字典(第一行数据是键)
import csv
data = csv.reader(open('files/2018年北京积分落户数据.csv', encoding='utf-8', newline=''))
data2 = csv.DictReader(open('files/2018年北京积分落户数据.csv', encoding='utf-8', newline=''))
- 获取迭代器中的内容
print(next(data)) # ['id', 'name', 'birthday', 'company', 'score']
print(next(data)) # ['1', '杨效丰', '1972-12', '北京利德华福电气技术有限公司', '122.59']
print(list(data))
print(next(data2)) # OrderedDict([('id', '1'), ('name', '杨效丰'),……],[……],……)
# 练习:计算积分平均分
data2 = csv.DictReader(open('files/2018年北京积分落户数据.csv', encoding='utf-8', newline=''))
scores = [eval(x['score']) for x in data2]
print('平均分:', f'{sum(scores) / len(scores):.2f}') # 平均分: 117.41
3.2 csv文件的写操作
1) 以列表为单位写入数据
# 1)创建writer
writer = csv.writer(open('files/students.csv', 'w', encoding='utf-8', newline=''))
# 2)写入数据
# 一次写一行数据
writer.writerow(['name', 'age', 'gender', 'tel', 'score']) # 写入表头
writer.writerow(['小明', 18, '男', '110', 98]) # 写入内容
# 同时写入多行数据
writer.writerows([
['小花', 22, '女', '123', 92],
['张三', 30, '男', '119', 78],
['小红', 20, '女', '114', 84]
])
2)以字典为单位写入数据
# 1)创建writer: csv.DictWriter(文件对象, 键对应的列表(表头))
writer = csv.DictWriter(
open('files/students2.csv', 'w', encoding='utf-8', newline=''),
['name', 'age', 'gender', 'tel', 'score']
)
# 2)写入数据
# 写入头部数据(键字典的键直接写入到第一行)
writer.writeheader()
# 一次写一行数据
writer.writerow({'name': '小明', 'age': 19, 'gender': '男', 'tel': '110', 'score': 100})
# 同时写入多行数据
writer.writerows([
{'name': '小红', 'age': 22, 'gender': '女', 'tel': '119', 'score': 97},
{'name': '小花', 'age': 24, 'gender': '女', 'tel': '120', 'score': 88}
])
入到第一行)
writer.writeheader()
# 一次写一行数据
writer.writerow({'name': '小明', 'age': 19, 'gender': '男', 'tel': '110', 'score': 100})
# 同时写入多行数据
writer.writerows([
{'name': '小红', 'age': 22, 'gender': '女', 'tel': '119', 'score': 97},
{'name': '小花', 'age': 24, 'gender': '女', 'tel': '120', 'score': 88}
])