python面向对象

面向对象

概述

面向对象三大特征:继承性,封装性,多态性

 

封装

# 定义汽车类
class Car():
def byCar(self):
print("载人去天安门广场")
def move(self):
print("汽车发动")
def ac(self):
print("打开空调")

car = Car()
car.byCar()
car.move()
car.ac()

class Hero():
def __init__(self,name,hp,atk,armor):
self.name = name
self.hp = hp
self.atk = atk
self.armor = armor

def info(self):
print(self.name)
print(self.hp)
print(self.atk)
print(self.armor)
print("self各不同,对象是出处")

def move(self):
print("英雄移动了")

def attack(self):
print("你的英雄发动攻击了")

def __str__(self):
return "英雄 <%s> 数据:生命值:%d,攻击力:%d,护甲值:%d" % (self.name, self.hp, self.atk, self.armor)

def __del__(self):
print(f"啊我死了,{self.name}")

luban = Hero("鲁班七号",2600,450,200)
luban.info()
luban.move()
luban.attack()
id(luban)
print(luban)

houyi = Hero("后羿",4500,380,400)
houyi.info()
houyi.move()
houyi.attack()
id(houyi)
print(houyi)

继承
class Master(object):
def __init__(self):
self.kongfu = "古法煎饼果子配方"

def make_cake(self):
print(f"使用了{self.kongfu},制作了一个煎饼果子")

class School(object):
def __init__(self):
self.kongfu = "现代煎饼果子配方"
def make_cake(self):
print(f"使用{self.kongfu}制作了一个煎饼果子")
def play_game(self):
print(f"打败了鲁班七号")

class DaMao(School,Master):
def __init__(self):
self.kongfu = "改良了配方"
pass

damao= DaMao()
damao.make_cake()
damao.play_game()
print(damao.__mro__)


#说明:
#多继承可以继承多个父类,也继承了所有父类的属性和方法
#注意:如果多个父类中同名的属性和方法,则默认使用第一个父类的属性和方法(根据类的魔法属性mro的顺序来查找)
#多个父类中,不重名的属性和方法,不会有任何影响


多态
class Master(object):
def __init__(self):
self.kongfu = "古法煎饼果子配方"

def make_cake(self):
print(f"使用了{self.kongfu},制作了一个煎饼果子")

class School(object):
def __init__(self):
self.kongfu = "现代煎饼果子配方"
def make_cake(self):
print(f"使用{self.kongfu}制作了一个煎饼果子")
def play_game(self):
print(f"打败了鲁班七号")

class DaMao(School,Master):
def __init__(self):
self.kongfu = "猫式配方"

def make_cake(self):
print(f"使用{self.kongfu}制作了一个煎饼果子")
def make_old_cake(self):
Master.__init__(self)
self.make_cake()

def make_moder_cake(self):
School.__init__(self)
self.make_cake()
School.make_cake()

damao= DaMao()
print(DaMao.__mro__)
damao.make_cake()
damao.make_old_cake()
damao.make_moder_cake()
damao.play_game()

#说明:
#多继承可以继承多个父类,也继承了所有父类的属性和方法
#注意:如果多个父类中同名的属性和方法,则默认使用第一个父类的属性和方法(根据类的魔法属性mro的顺序来查找)
#多个父类中,不重名的属性和方法,不会有任何影响

class PrenticePrentice(DaMao):
pass
#属性前加"_"代表私有,可以利用super调用私有的属性和方法
 
posted @ 2022-08-23 18:19  仿生言子  阅读(53)  评论(0)    收藏  举报