链接: python基础(上篇).
链接: python基础(下篇).
链接: python基础这(模块篇).
面向对象编程(下)进阶
私有化属性
class Person:
__hobby='跳舞'
def __init__(self):
self.__name='李四'
self.age=30
pass
def __str__(self):
'''
私有化的属性在内部可以使用
:return:
'''
return '{}的年龄是{},爱{}'.format(self.__name,self.age,self.__hobby)
x1=Person()
print(x1)
class student(Person):
def printInfo(self):
print(self.__name)
pass
stu=student()
私有化方法
class animal:
def __eat(self):
print('吃东西')
pass
def run(self):
self.__eat()
print('飞快的跑')
pass
pass
class Bird(animal):
pass
b1=Bird()
b1.run()
关于私有化属性的property属性
class Person(object):
def __init__(self):
self.__age=18
pass
@property
def age(self):
return self.__age
@age.setter
def age(self,age):
if age<0:
print('年龄不能小于0')
pass
else:
self.__age=age
pass
pass
p1=Person()
print(p1.age)
p1.age=25
print(p1.age)
动态添加属性和方法
import types
def dynamicSort(self):
print('{}的体重是{}kg,在{}读大学'.format(self.name,self.weight,Student.school))
@classmethod
def classTest(cls):
print('这是一个类方法')
pass
@staticmethod
def staticMethond():
print('这是一个静态方法')
pass
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return '{}今年{}岁'.format(self.name,self.age)
pass
Student.TestMethod=classTest
Student.TestMethod()
print('-----------------类方法结束----------------')
Student.staticMethod=staticMethond
Student.staticMethod()
print('------------------静态方法结束--------------')
wy=Student('王钰',14)
wy.weight=50
wy.PrintInfo=types.MethodType(dynamicSort,wy)
Student.school='北京邮电大学'
print('---------------执行动态方法的绑定-----------------------')
wy.PrintInfo()
zm=Student('张明',20)
new和单例模式
class animal:
def __init__(self):
self.color='红色'
pass
def __new__(cls,*args,**kwargs):
return super().__new__(cls,*args,**kwargs)
pass
tigger=animal()
class DataBassClass(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls,'_instance'):
cls._instance=super().__new__(cls,*args,**kwargs)
return cls._instance
pass
db1=DataBassClass()
print(id(db1))
db2=DataBassClass()
print(id(db2))
class Db(DataBassClass):
pass
D1=Db()
print(id(D1))
__slots__属性
class Student(object):
__slots__ = ('name','age','score')
def __str__(self):
return '{}..{}..{}'.format(self.name,self.age,self.score)
xw=Student()
xw.name='小王'
xw.age=20
xw.score=100
print(xw)
class test(Student):
pass
wpc=test()
wpc.pro='计算机科学与技术'
print(wpc.pro)
错误方法与异常处理
try:
print(b)
pass
except Exception as result:
print(result)
def A(s):
return 10/int(s)
def B(s):
return A(s)*2
def main():
try:
B("0")
pass
except Exception as msg:
print(msg)
pass
pass
main()
try:
print (aa)
pass
except Exception as msg:
print(msg)
else:
print('当Try里面的代码 没有出现异常的情况下 我才会执行')
try:
pass
except Exception as msg:
print(msg)
pass
finally:
print('释放文件的资源、数据库链接时资源等等')
print('不管有没有错都执行的代码块')
class ToolongMyException(Exception):
def __init__(self,length):
'''
:param length:长度
'''
self.length=length
pass
def __str__(self):
return '您输入的姓名数据长度是'+str(self.length)+'超过长度了..'
def name_Test():
name=input('请输入名字')
try:
if len(name)>5:
raise ToolongMyException(len(name))
else:
print(name)
except ToolongMyException as result:
print(result)
pass
finally:
print('执行完毕了....')
name_Test()
面向对象编程的作业
class Person:
def __init__(self):
self.__name='王钰'
self.__age=14
def __str__(self):
return '{}的年龄是{}'.format(self.__name,self.__age)
def getName(self):
return self.__name
def getAge(self):
return self.__age
def setName(self,name):
self.__name=name
def setAGE(self,age):
if age>120:
print('设置失败,超出年龄范围')
else:
self.__age=age
class Student:
def __init__(self):
self.__name='王钰'
self.__score=90
@property
def name(self):
return self.__name
@name.setter
def name(self,name):
self.__name=name
@property
def score(self):
return self.__score
@score.setter
def score(self,score):
self.__score=score
pass
def __str__(self):
return self.name
def __call__(self, *args, **kwargs):
print('{}的得分是:{}'.format(self.name,self.score))
pass
pass
xw=Student()
xw()
print(xw)
xw.name='李四'
xw.score=90
xw()
import types
def run(self):
print('奔跑')
pass
@classmethod
def printing(cls):
print('ok')
class animal:
pass
cat=animal()
cat.run=types.MethodType(run,cat)
animal.printing=printing
cat.printing()
animal.color='红色'
面向对象编程的究极案例,飞机大战游戏
pygame库安装
安装pygame时直接打开cmd 输入pip intall pygame安装即可
在创建Pycharm project工程时,在terminal中找到local
输入pip list试一试是否安装成功pygame,如果没有,再试试命令pip intall pygame
如果发现有错误
那么复制cmd中你pygame所安装的地址
拷贝到你所建立的pycharm项目中lib文件及下面。
具体代码
代码
import pygame
from pygame.locals import *
import random
import time
class player(object):
def __init__(self,screen):
self.x=250
self.y=550
self.screen=screen
self.imageName='./sucai/player_plane.png'
self.image=pygame.image.load(self.imageName)
self.bulletList=[]
pass
def leftMove(self):
if self.x>0:
self.x-=25
pass
def rightMove(self):
if self.x<450:
self.x+=25
pass
pass
def display(self):
self.screen.blit(self.image,(self.x,self.y))
needDeltItemList=[]
for item in self.bulletList:
if item.judge():
needDeltItemList.append(item)
pass
pass
for i in needDeltItemList:
self.bulletList.remove(i)
pass
for bullet in self.bulletList:
bullet.disPlay()
bullet.moveUp()
def sheBullet(self):
newBUllet=Bullet(self.x,self.y,self.screen)
self.bulletList.append(newBUllet)
pass
class Bullet:
def __init__(self,x,y,screen):
self.x=x+23
self.y=y+40
self.screen=screen
self.image=pygame.image.load('./sucai/player_bullet.png')
pass
def disPlay(self):
self.screen.blit(self.image,(self.x,self.y))
pass
def moveUp(self):
self.y-=0.1
pass
def judge(self):
if self.y<0:
return True
else:
return False
pass
def key_control(playerObject):
'''
通过定义普通的函数 来实现键盘的检测
:param playerObject:控制检测的对象
:return:
'''
eventList=pygame.event.get()
for event in eventList:
if event.type==QUIT:
print('退出')
exit()
pass
elif event.type==KEYDOWN:
if event.type==K_a or event.key==K_LEFT:
print('left')
playerObject.leftMove()
pass
elif event.type==K_d or event.key==K_RIGHT:
print('right')
playerObject.rightMove()
pass
elif event.key==K_SPACE:
print('k_SPACE')
playerObject.sheBullet()
class enemy:
def __init__(self,screen):
self.dirction='right'
self.x=0
self.y=0
self.screen=screen
self.image=pygame.image.load('./sucai/enemy_plane.png')
self.bulletList=[]
pass
def disPlay(self):
'''
显示敌机以及位置的信息
:return:
'''
self.screen.blit(self.image,(self.x,self.y))
needDeltItemList=[]
for item in self.bulletList:
if item.judge():
needDeltItemList.append(item)
pass
pass
for i in needDeltItemList:
self.bulletList.remove(i)
pass
for bullet in self.bulletList:
bullet.disPlay()
bullet.moveUp()
def shoot(self):
'''
敌机随机的发射子弹
:return:
'''
num=random.randint(1,255)
if num==3:
newBullet=enemyBullet(self.x,self.y,self.screen)
self.bulletList.append(newBullet)
pass
def move(self):
if self.dirction=='right':
self.x+=0.1
elif self.dirction=='left':
self.x-=0.1
if self.x>500-20:
self.dirction='left'
elif self.x<0:
self.dirction='right'
pass
pass
pass
class enemyBullet:
def __init__(self,x,y,screen):
self.x=x+23
self.y=y+40
self.screen=screen
self.image=pygame.image.load('./sucai/enemy_bullet.png')
pass
def disPlay(self):
self.screen.blit(self.image,(self.x,self.y))
pass
def moveUp(self):
self.y+=0.1
pass
def judge(self):
if self.y>550:
return True
else:
return False
pass
def main():
screen=pygame.display.set_mode((500,600))
background=pygame.image.load('./sucai/backgroud.webp')
pygame.display.set_caption('特朗普大战拜登')
pygame.mixer.init()
pygame.mixer.music.load('./sucai/backgroud_music.mp3')
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(-1)
hero=player(screen)
baideng=enemy(screen)
while True:
screen.blit(background,(0,0))
hero.display()
baideng.disPlay()
baideng.move()
baideng.shoot()
key_control(hero)
pygame.display.update()
pass
main()
代码优化之后
import pygame
from pygame.locals import *
import random
import time
class BassPlane(object):
def __init__(self,screen,imagePath):
'''
初始化基类函数
:param screen:主窗体函数
:param imagePath: 加载的图片
'''
self.screen=screen
self.image=pygame.image.load(imagePath)
self.bulletList=[]
pass
def disPlay(self):
self.screen.blit(self.image,(self.x,self.y))
needDeltItemList=[]
for item in self.bulletList:
if item.judge():
needDeltItemList.append(item)
pass
pass
for i in needDeltItemList:
self.bulletList.remove(i)
pass
for bullet in self.bulletList:
bullet.disPlay()
bullet.move()
class commomBullet(object):
'''
公共子弹类
'''
def __init__(self,x,y,screen,bulletType):
self.type=bulletType
self.screen=screen
if self.type=='Player':
self.x=x+26
self.y=y-40
self.imagePath='./sucai/player_bullet.png'
elif self.type=='enemy':
self.x=x+20
self.y=y+45
self.imagePath='./sucai/enemy_bullet.png'
self.image=pygame.image.load(self.imagePath)
pass
def move(self):
'''
子弹的移动
:return:
'''
if self.type=='Player':
self.y-=0.1
elif self.type=='enemy':
self.y+=0.1
pass
pass
def disPlay(self):
self.screen.blit(self.image,(self.x,self.y))
def judge(self):
if self.y>550 or self.y<0:
return True
else:
return False
pass
pass
class player(BassPlane):
def __init__(self,screen):
'''
初始化函数
:param screen:
'''
super().__init__(screen,'./sucai/player_plane.png')
self.x=250
self.y=550
def leftMove(self):
if self.x>0:
self.x-=25
pass
def rightMove(self):
if self.x<450:
self.x+=25
pass
pass
def sheBullet(self):
newBUllet=commomBullet(self.x,self.y,self.screen,'Player')
self.bulletList.append(newBUllet)
pass
def key_control(playerObject):
'''
通过定义普通的函数 来实现键盘的检测
:param playerObject:控制检测的对象
:return:
'''
eventList=pygame.event.get()
for event in eventList:
if event.type==QUIT:
print('退出')
exit()
pass
elif event.type==KEYDOWN:
if event.type==K_a or event.key==K_LEFT:
print('left')
playerObject.leftMove()
pass
elif event.type==K_d or event.key==K_RIGHT:
print('right')
playerObject.rightMove()
pass
elif event.key==K_SPACE:
print('k_SPACE')
playerObject.sheBullet()
class enemy(BassPlane):
def __init__(self,screen):
super().__init__(screen,'./sucai/enemy_plane.png')
self.dirction='right'
self.x=0
self.y=0
pass
def shoot(self):
'''
敌机随机的发射子弹
:return:
'''
num=random.randint(1,1000)
if num==3:
newBullet=commomBullet(self.x,self.y,self.screen,'enemy')
self.bulletList.append(newBullet)
pass
def move(self):
if self.dirction=='right':
self.x+=0.1
elif self.dirction=='left':
self.x-=0.1
if self.x>500-20:
self.dirction='left'
elif self.x<0:
self.dirction='right'
pass
pass
pass
def main():
screen=pygame.display.set_mode((500,600))
background=pygame.image.load('./sucai/backgroud.webp')
pygame.display.set_caption('特朗普大战拜登')
pygame.mixer.init()
pygame.mixer.music.load('./sucai/backgroud_music.mp3')
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(-1)
hero=player(screen)
baideng=enemy(screen)
while True:
screen.blit(background,(0,0))
hero.disPlay()
baideng.disPlay()
baideng.move()
baideng.shoot()
key_control(hero)
pygame.display.update()
pass
|