第七章 面向对象
7.1 面向对象的基本格式
class 类:
def 方法名(self,name)
print(name)
return 123
def 方法名(self,name)
print(name)
return 123
def 方法名(self,name)
print(name)
return 123
应用场景:遇到很多函数,需要给函数进行分类规划【封装】
7.2对象的作用
存储一些值,方便以后调用
class File:
def read(self):
with open(self.xxx,mode='r',encoding='utf-8') as f:
data = read()
return data
def write(self,content):
with open(self.xxx,mode='w',encoding='uttf-8') as f:
f.write(content)
class Person:
def show(self):
temp = "我是%s,今年%s岁,性别%s" %(self.name,self.age,self.gender)
print(temp)
obj = Person()
obj.name = 'liujia'
obj.age = 2
obj.gender = 'boy'
obj.show()
class Person:
def __init__(self,n,a,g)
总结:将数据封装到对象中,方便使用
"""
如果写代码时,函数比较多比较乱。
1. 可以将函数归类并放到同一个类中。
2. 函数如果有一个反复使用的公共值,则可以放到对象中。
"""
class File:
def __init__(self,path):
self.file_path = path
def read(self):
print(self.file_path)
def write(self,content):
print(self.file_path)
def delete(self):
print(self.file_path)
def update(self):
print(self.file_path)
p1 = File('log.txt')
p1.read()
p2 = File('xxxxxx.txt')
p2.read()
示例:游戏开发
class Police:
def __init__(self,name)
self.name = name
self.hp = 10000
def tax(self):
msg = "%s收了个税。" %(self.name,)
print(msg)
def fight(self):
msg = "%s去战了个斗。" %(self.name,)
lsq = Police('李邵奇')
zzh = Police('渣渣会')
tyg = Police('堂有光')
class Bandit:
def __init__(self,nickname)
self.nickname = nickname
self.hp = 1000
def murder(self,name):
msg = "%s去谋杀了%s" %(self.nickname, name,)
lcj = Bandit('二蛋')
lp = Bandit('二狗')
zsd = Bandit('狗蛋')
class Police:
def __init__(self,name)
self.name = name
self.hp = 10000
def dao(self,other):
msg = "%s个了%s一刀。" %(self.name,other.nickname)
self.hp = self.hp - 10
other.hp = other.hp - 50
print(msg)
def qiang(self):
msg = "%s去战了个斗。" %(self.name,)
def quan(self,other):
msg = "%s个了%s一全。" %(self.name,other.nickname)
self.hp = self.hp - 2
other.hp = other.hp - 10
print(msg)
class Bandit:
def __init__(self,nickname)
self.nickname = nickname
self.hp = 1000
def qiang(self,other):
msg = "%s个了%s一全。" %(self.nickname,other.name)
self.hp -= 20
other.hp -= 500
lcj = Bandit('二蛋')
lsq = Police('李邵奇')
lsq.dao(lcj)
lsq.quan(lcj)
lcj.qiang(lsq)
7.3 继承
问题:什么时候才能用到继承?多个类中如果有公共的方法,可以放到基类中避免重负编写
class Base:
def f1(self):
pass
class Foo(Base):
def f2(self):
pass
class Bar(Base):
def f3(self):
pass
obj1 = Foo()
obj2 = Bar()
继承关系中查找方法的顺序: