1??recode
1.json數(shù)據(jù)
json數(shù)據(jù)的要求:
a.一個(gè)json對(duì)應(yīng)一個(gè)數(shù)據(jù)
b.json中的數(shù)據(jù)一定是json支持的數(shù)據(jù)類型
數(shù)字:整數(shù)和小數(shù)
字符串:雙引號(hào)引起來的內(nèi)容
數(shù)組:[120, "anc", true, [1, 2], {"a":123}]
字典: {"abc":120, "aa":"abc", "list":[1, 2]}
布爾: true/false
null: 空(None)
json模塊:
load(文件對(duì)象) --> 將文件中的內(nèi)容讀出來震放,轉(zhuǎn)換成python對(duì)應(yīng)的數(shù)據(jù)
dump(內(nèi)容, 文件對(duì)象) --> 將內(nèi)容以json格式,寫入到文件中
loads(字符串) --> 將json格式字符串轉(zhuǎn)換成python數(shù)據(jù) '{"a": 12}'
dumps(python數(shù)據(jù)) --> 將python數(shù)據(jù)轉(zhuǎn)換成json格式的字符串
2.異常處理
t>ry-except-finally語法捕獲異常
raise語法拋出異常
a.
try:
代碼1
except:
代碼2
try:
代碼1
except (異常類型1,異常類型2...):
代碼2
try:
代碼1
except 異常類型1:
代碼2
except 異常類型2:
代碼3
b. raise 錯(cuò)誤類型
錯(cuò)誤類型:必須是Exception的子類(系統(tǒng)的錯(cuò)誤類型和自定義的類型)
自定義錯(cuò)誤類型:寫一個(gè)類繼承Exception鲤桥,重寫str方法定制錯(cuò)誤提示語
3.類和對(duì)象
a.類的聲明
class 類名(父類列表):
類的內(nèi)容
b.創(chuàng)建對(duì)象
對(duì)象 = 類名()
c.類的字段和對(duì)象的屬性
類的字段:
對(duì)象的屬性:init方法误澳,self.屬性=值
d.對(duì)象方法佣盒,類方法,靜態(tài)方法
對(duì)象方法:
類方法:@classmethod
靜態(tài)方法:@staticmethod
e.對(duì)象屬性的增刪改查
f.私有化:名字前加__
g.getter和setter
h.常用的內(nèi)置屬性: 對(duì)象.dict, 對(duì)象.class, 類.name
i.繼承:所有類都默認(rèn)繼承object凫佛,繼承哪些東西语婴,重寫(super()), 添加對(duì)象屬性
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
# 補(bǔ)充1: 拋出異常
class MyError(Exception):
def __str__(self):
return '需要一個(gè)偶數(shù),但是給了一個(gè)奇數(shù)'
number = int(input('請(qǐng)輸入一個(gè)偶數(shù):'))
if number & 1:
raise MyError
# 補(bǔ)充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__(10)
self.color = color
# 注意:多繼承的時(shí)候溶握,只能繼承第一個(gè)父類的對(duì)象屬性(創(chuàng)建對(duì)象的時(shí)候調(diào)用的是第一個(gè)父類的對(duì)象方法)
# 一般在需要繼承多個(gè)類的功能的時(shí)候用
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
# 將對(duì)象保存到本地
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)
# 將字典列表轉(zhuǎn)換成對(duì)象列表
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 = '斗狗'
# 將不同類型的對(duì)象添加到不同的json文件中
def add_object_json2(obj: object):
file_name = obj.__class__.__name__+'.json'
# 獲取原文中的內(nèi)容
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('學(xué)生:', get_all_info(Student))
print('狗:', get_all_info(Dog))
問題:怎么將對(duì)象寫入json文件中?怎么將json中的字典讀出后轉(zhuǎn)換成相應(yīng)的對(duì)象蒸播?
2??抽象類和抽象方法
抽象類:只能被繼承不能實(shí)例化(不能創(chuàng)建對(duì)象)
抽象方法:聲明的時(shí)候不用實(shí)現(xiàn)睡榆。在子類中必須去重寫的方法
怎么去聲明抽象類:類繼承abc模塊中的ABCMeta,繼承的時(shí)候需要加參數(shù)metaclass袍榆。并且要通過abstractmethod來聲明抽象方法
子類繼承一個(gè)抽象類胀屿,必須在子類中實(shí)現(xiàn)抽象類中所有的抽象方法
metaclass -> 元類
import abc
class Shape(metaclass=abc.ABCMeta):
# 聲明抽象方法
@abc.abstractmethod
def draw(self):
pass
class Circle(Shape):
def draw(self):
print('畫圖畫')
# s1 = Shape() 抽象類不能實(shí)例化
3??pygame的圖片顯示
display --> 屏幕相關(guān)
event --> 事件相關(guān)
draw --> 圖形
image --> 圖片
font --> 字體
import pygame
# 1.初始化游戲
pygame.init()
# 2.創(chuàng)建窗口對(duì)象
"""
set_mode(size) -->size是元祖:(長,寬)包雀,單位是像素
紅色:(255, 0, 0)
綠色:(0, 255, 0)
白色:(255, 255, 255)
黑色:(0, 0, 0)
黃色:(255, 255, 0)
"""
screen = pygame.display.set_mode((600, 400))
"""
fill(顏色) --> 填充指定的顏色
計(jì)算機(jī)使用的是計(jì)算機(jī)三原色(紅宿崭、綠、藍(lán)) --> rgb顏色,對(duì)應(yīng)的值的范圍是0~255
"""
screen.fill((255, 255, 255))
# 4.顯示圖片
"""
1.加載圖片
load(圖片) -> 返回圖片對(duì)象
"""
image = pygame.image.load('./files/Mario.png')
"""
a.獲取圖片的大小
圖片_get_size() -->返回的大小結(jié)果是個(gè)元祖
"""
image_width, image_height = image.get_size()
"""
b.對(duì)圖片進(jìn)行縮放
transform.scale(圖片對(duì)象才写,大小) --> 將指定的圖片縮放成指定的大小,返回一個(gè)新的圖片
注意:這種縮放葡兑,可能會(huì)讓圖片發(fā)生形變
"""
new_image1 = pygame.transform.scale(image, (50, 50))
"""
c.對(duì)圖片進(jìn)行縮放和旋轉(zhuǎn)
transform.rotozoom(圖片對(duì)象,旋轉(zhuǎn)角度赞草,縮放比例)
比例:原圖的多少倍讹堤,放大:大于一,縮谐怼:小于一
角度:0~360
"""
new_image2 = pygame.transform.rotozoom(image, 45, 1.5)
"""
2.渲染圖片
blit(渲染對(duì)象洲守,渲染位置)
位置渲染 -> 元祖,(x坐標(biāo),y坐標(biāo))
"""
screen.blit(new_image2, (0, 0))
"""
3.展示內(nèi)容沾凄,只要想將內(nèi)容展示在屏幕上梗醇,都必須調(diào)用這個(gè)方法
"""
pygame.display.flip()
# 3.游戲循環(huán)(不斷檢測(cè)是否有事件發(fā)生)
while True:
# 不斷檢測(cè)事件的產(chǎn)生
for event in pygame.event.get():
# 不同類型的事件,event的type屬性不同
if event.type == pygame.QUIT:
exit() # 程序結(jié)束
4??文字顯示
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))
pygame.display.flip()
顯示文字
1.創(chuàng)建字體對(duì)象
SysFont(字體名撒蟀,字體大小叙谨,是否加粗=False,是否傾斜=False) --> 創(chuàng)建系統(tǒng)字體對(duì)象
Font(字體文件路徑牙肝,字體大小) --> 自定義字體
"""
# font = pygame.font.SysFont('NewTime', 120, italic=False)
font = pygame.font.Font('./files/aa.ttf', 50)
"""
2.根據(jù)字體創(chuàng)建文字對(duì)象
字體對(duì)象.render(文字唉俗,是否抗鋸齒嗤朴,顏色)
"""
text = font.render('嗷嗷hello python', True, (0, 255, 255))
"""
3.在屏幕上渲染文字
"""
screen.blit(text, (100, 100))
"""
4.展示在窗口上
"""
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
5??圖形顯示
import pygame
import random
def rand_color():
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))
# 畫圖
"""
1.畫線
def line(Surface, color, start_pos, end_pos, width=1)
Surface:窗口,圖片虫溜,文字對(duì)象
color:線的顏色
start_pos, end_pos: 起點(diǎn)和終點(diǎn)(坐標(biāo))
width:寬度
"""
pygame.draw.line(screen, (0, 0, 0), (50, 50), (100, 100), 20)
"""
def lines(Surface, color, closed, pointlist, width=1)
closed:是否鏈接起點(diǎn)和終點(diǎn)
pointlist:列表雹姊,列表中的元素是點(diǎn)對(duì)應(yīng)的元祖
"""
"""
2.畫圓
def circle(Surface, color, pos, radius, width=1)
"""
"""
def arc(Surface, color, Rect, start_angle, stop_angle, width=1)
Rect:(x, y, width, height)
"""
pygame.draw.circle(screen, (250, 152, 112), (300, 200), 150, 0)
pygame.draw.lines(screen, (0, 0, 0), 1, [(150, 20), (80, 90), (20, 60), (200, 100)], 1)
from math import pi
screen.fill((255, 255, 255))
pygame.draw.arc(screen, rand_color(), (100, 200, 200, 100), 0, 2*pi, 5)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
6??python事件
"""
鼠標(biāo)事件
pygame.MOUSEBUTTONDOWN: -->鼠標(biāo)按下
pygame.MOUSEBUTTONUP: -->鼠標(biāo)彈起
pygame.MOUSEMOTION: -->鼠標(biāo)移動(dòng)
鍵盤事件
"""
import pygame
import random
def rand_color():
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
# 鼠標(biāo)按下后要做什么事情就寫在這
screen.fill((255, 255, 255))
pygame.display.flip()
print('鼠標(biāo)按下:', event.pos)
if event.type == pygame.MOUSEBUTTONUP:
# 鼠標(biāo)按下后彈起
print('鼠標(biāo)彈起', event.pos)
if event.type == pygame.MOUSEMOTION:
# 鼠標(biāo)移動(dòng)
pygame.draw.circle(screen, rand_color(), event.pos, 20)
pygame.display.flip()
print('鼠標(biāo)移動(dòng)', event.pos)
# ==============鍵盤事件===============
if event.type == pygame.KEYDOWN:
print('鍵盤按下', event.key, chr(event.key))
if event.type == pygame.KEYUP:
print('鍵盤彈起', event.key, chr(event.key))