美文网首页
一阶段day17-03面向对象应用

一阶段day17-03面向对象应用

作者: ATM_shark | 来源:发表于2018-10-22 20:34 被阅读0次

1.json数据

json数据的要求:
a.一个json对应一个数据
b.json中的数据一定是json支持的数据类型

数字:整数和小数
字符串:双引号引起来的内容
数组:[120, "anc", true, [1, 2], {"a":123}]
字典: {"abc":120, "aa":"abc", "list":[1, 2]}
布尔: true/false
null: 空(None)

json模块:
load(文件对象) --> 将文件中的内容读出来,转换成python对应的数据
dump(内容, 文件对象) --> 将内容以json格式,写入到文件中

loads(字符串) --> 将json格式字符串转换成python数据 '{"a": 12}'
dumps(python数据) --> 将python数据转换成json格式的字符串

2.异常处理

try-except-finally语法捕获异常
raise语法抛出异常

a.
try:
代码1
except:
代码2

try:
代码1
except (异常类型1,异常类型2...):
代码2

try:
代码1
except 异常类型1:
代码2
except 异常类型2:
代码3

b. raise 错误类型
错误类型:必须是Exception的子类(系统的错误类型和自定义的类型)
自定义错误类型:写一个类继承Exception,重写str方法定制错误提示语

3.类和对象

a.类的声明
class 类名(父类列表):
类的内容

b.创建对象
对象 = 类名()

c.类的字段和对象的属性
类的字段:
对象的属性:init方法,self.属性=值

d.对象方法,类方法,静态方法
对象方法:
类方法:@classmethod
静态方法:@staticmethod

e.对象属性的增删改查
f.私有化:名字前加__
g.getter和setter
h.常用的内置属性: 对象.dict, 对象.class, 类.name
i.继承:所有类都默认继承object,继承哪些东西,重写(super()), 添加对象属性

class Perosn(object):
    def __init__(self):
        self._age = 0

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        self._age = value

补充1: 抛出异常

class MyError(Exception):
    def __str__(self):
        return '需要一个偶数,但是给了一个奇数'


number = int(input('请输入一个偶数:'))
if number & 1:
     raise MyError

补充2:多继承

class Animal:
    num = 10
    def __init__(self, age):
        self.age = age

    def run(self):
        print('可以跑')

print(Animal.__dict__)

class Fly:
    def __init__(self, height):
        self.height = height

    def can_fly(self):
        print('可以飞')


class Bird(Animal, Fly):
    def __init__(self, color):
        super().__init__(age,height)
        self.color = color

# 注意:多继承的时候,只能继承第一个父类的对象属性(创建对象的时候调用的是第一个父类的对象方法)
# 一般在需要继承多个类的功能的时候用
b1 = Bird('abc')
b1.age = 18
b1.height = 200
print(b1.age)
print(b1.height)
b1.can_fly()
b1.run()

============================

对象与本地文件的操作应用

class Student:
    def __init__(self, name='', age=0, tel=''):
        self.name = name
        self.age = age
        self.tel = tel
        self.sex = '男'

    def show_info(self):
        print(self.__dict__)

    def __repr__(self):
        return '<'+str(self.__dict__)[1:-1]+'>'


all_students = [Student('小明', 18, '1278763'),
                Student('xiaohua', 12, '127723')
                ]

class Dog:
    def __init__(self):
        self.name = ''
        self.age = 0
        self.color = ''
        self.type = ''
    def __repr__(self):
        return '<'+str(self.__dict__)[1:-1]+'>'

import json


# 将对象保存到本地
def object_json(file, content):
    with open('./'+file, 'w', encoding='utf-8') as f:
        new = []
        for stu in content:
            new.append(stu.__dict__)
        json.dump(new, f)

object_json('test.json', all_students) 

===================================
# 将字典列表转换成对象列表
def json_object(file, type):
    with open('./'+file, 'r', encoding='utf-8') as f:
        list1 = json.load(f)
        all_value = []
        for dict1 in list1:
            object = type()
            for key in dict1:
                setattr(object, key, dict1[key])
            all_value.append(object)
    return all_value


print(json_object('test.json', Student))
print(json_object('test2.json', Dog))

=========================================
stu = Student('xiaoming', 12, '231273')  # Student.json

dog1 = Dog()   # Dog.json
dog1.name = 'XiaoHua'
dog1.age = 3
dog1.color = '黄色'
dog1.type = '斗狗'


# 将不同类型的对象添加到不同的json文件中
def add_object_json2(obj: object):
    file_name = obj.__class__.__name__+'.json'

    # 获取原文中的内容
    try:
        with open('./'+file_name, encoding='utf-8') as f:
            list1 = json.load(f)
    except FileNotFoundError:
        list1 = []

    with open('./'+file_name, 'w', encoding='utf-8') as f:
        list1.append(obj.__dict__)
        json.dump(list1, f)



add_object_json2(stu)
add_object_json2(dog1)


def get_all_info(type):
    file = type.__name__+'.json'
    with open('./'+file, 'r', encoding='utf-8') as f:
        list1 = json.load(f)
        all_value = []
        for dict1 in list1:
            object = type()
            for key in dict1:
                setattr(object, key, dict1[key])
            all_value.append(object)
    return all_value

print('学生:', get_all_info(Student))
print('狗:', get_all_info(Dog))

"""
问题:怎么将对象写入json文件中?怎么将json中的字典读出后转换成相应的对象?
"""

相关文章

  • 一阶段day17-03面向对象应用

    1.json数据 json数据的要求:a.一个json对应一个数据b.json中的数据一定是json支持的数据类型...

  • Python基础入门 - 面向对象

    1. 初识面向对象 1.1 介绍 步骤介绍面向对象的概述面向对象的实现面向对象的应用内存管理进程、线程、协程 概要...

  • PHP面试题6--面向对象基础

    什么是面向对象 定义:面向对象(Object Oriented, OO)是软件开发方法。面向对象的概念和应用已超越...

  • 面向对象

    1.【应用】面向对象概述 a. 【理解】能够阐述面向对象思想与面向过程思想的特点 A:什么是面向过程面向过程,其实...

  • 面向上帝

    面向过程编程,面向对象,面向映射又或者叫面向函数,。。。面向组件。。。面向应用,面向服务器,面向AI,面向类人.....

  • 面向对象具体应用

    1、抽象类 1.1实例 描述:定义一个抽象类Shape,具有受保护类型的x和y属性,以及公有的抽象方法获得面积。R...

  • 面向对象的应用

    1.面向对象 面向对象有什么用呢,继承有什么用呢,其实用处很大。就是可以减少代码的重复使用,化繁为简。把重复的代码...

  • 面向对象编程应用

    面向对象编程对初学者来说不难理解但很难应用,虽然我们为大家总结过面向对象的三步走方法(定义类、创建对象、给对象发消...

  • Scala语言学习四 (类和对象)

    类和对象 scala是支持面向对象的,也有类和对象的概念。我们依然可以基于scala语言来开发面向对象的应用程序。...

  • 什么是面向对象编程思想?

    一、面向对象是什么 面向对象 (Object Oriented,OO) 的思想对软件开发相当重要,它的概念和应用...

网友评论

      本文标题:一阶段day17-03面向对象应用

      本文链接:https://www.haomeiwen.com/subject/pihnzftx.html