一、封装
封装是指隐藏对象的属性和实现细节,仅对外提供公共访问的方式,同时封装也可以把同一类型的东西放在一起,通过self调用
作用:将变化隔离、便于使用、提高复用性、提高安全性
原则:将不需要对外提供的内容都隐藏起来,把属性都隐藏,提供公共方法对其访问
class People():
def __init__(self,name,age):
#类里的self实质就是对象本身
#self是对象,name是属性,self.name就是将对象和属性封装在一起
self.name = name
self.age = age
def run(self):
print('%s正在跑步...' %(self.name))
p1 = People('小李',38)
p1.run()
p2 = People('小王',36)
p2.run()
二、继承
继承是一种创建新类的方式,在python中新建的类可以继承一个或多个父类,父类又可称为基类或超类(Baseclass、Supperclass),新建的类称为扩展类(Subclass)或子类
1. 子类继承父类
class Father(): #父类
def __init__(self,name,age):
#构造方法在实例化对象时自动执行
self.name = name
self.age = age
def eat(self):
print('%s正在吃...' %(self.name))
def sleep(self):
print('%s正在睡...' %(self.name))
class Son(Father): #子类,继承父类
def eat(self): #方法重写(不使用父类中的eat方法)
# Father.eat(self) #方法一:父类和子类的eat方法同时打印
# super(Son,self).eat() #方法二:同时打印,建议使用该方法
print('%s倒立吃饭...' %(self.name))
father = Father('老王',65)
son = Son('小王',38)
son.eat()
father.sleep()
2. 继承的传递
继承具有传递性,子类拥有父类的属性和方法
class Animal():
def eat(self):
print('吃')
def drint(self):
print('喝')
def sleep(self):
print('睡')
class Cat(Animal):
def yell(self):
print('喵')
class Jiqimiao(Cat):
def speak(self):
print('我会说话')
def eat(self): #方法重写
print('eat')
jqm = Jiqimiao()
jqm.speak()
jqm.yell()
jqm.eat()
3. 多重继承
class A():
def test(self):
print('A ---- test')
def domo1(self):
print('A ---- domo')
class B():
def test(self):
print('B ---- test')
def domo(self):
print('B ---- domo')
class C(B,A): #多重继承
pass
c = C()
c.test()
c.domo1()
三、多态
多态指的是一类事物有多种型态
python语言天生自带多态的属性,所以该概念也是类比其他面向对象语言(Java)而言而提及的,因为类似Java等 其他面向对象的强类型语言中如果参数是对象的话前面的对象类型指代就是有问题,所以会用对象的父类来代替,这样表现出来的就是父类的子类都可以作为参数, 而调用不同的子类就会表现出不同的结果,也就是多态的表现;但是针对python语言而言是动态强类型语言所以不会发生该问题,即天生即解决了多态的问题。
class Student():
def get_score(self):
print('获取学生成绩')
class Chinese():
def get_score(self):
print('获取学生的语文成绩')
class Math():
def get_score(self):
print('获取学生的数学成绩')
student1 = Student() #创建不同的对象
student2 = Chinese()
student3 = Math()
student1.get_score() #调用相同的方法
student2.get_score()
student3.get_score()