封装(隐藏)
隐藏对象的属性和实现细节,只对外提供必要的方法,即相当于把细节封装起来。“私有属性,私有方法”,语法简洁,没有严格的语法级别访问控制符,更多依靠程序员自己实现。
继承
让子类拥有父类的特性,提高了代码的复用性
增量进化,父类设计不变,增加新的功能。
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def say_age(self):
print(self.name,self.age)
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)#必须显式调用
self.score=score
a=Student("筱明",21,200)
a.say_age()
类方法的继承和重写
重写即在子类中重新写方法,会首先调用子类
class Person:
def __init__(self,age,name):
self.age=age
self.name=name
def set_age(self):
print("我的名字是:",self.name)
def set_name(self):
print("我的年龄是{0}".format(self.age))
class Student(Person):
def __init__(self,age,name,score):
Person.__init__(self,name,age)
self.score=score
def set_name(self):
print("报告老师,我的名字是:{}".format(self.name))
c=Student(21,"王玉",80)
c.set_name()
查看类的继承层次结构
_mro_输出类的继承层次结构
用法:类.mro()
super可获得父类的方法
多态
一个方法调用,对象不同,
a.xiuxi()—张三:睡觉 李四:玩游戏
class Animal:
def shout(self):
print("动物叫了一声")
class Dog(Animal):
def shout(self):
print("汪汪汪")
class Cat(Animal):
def shout(self):
print("喵喵喵")
def AnimalShout(m):
if isinstance(m,Animal):
m.shout()
AnimalShout(Dog())
AnimalShout(Cat())
AnimalShout(Animal())
组合
is-a关系
继承:dog是animal
has-a关系
组合:手机有一个cpu
工厂模式
实现了创建者和调用者的分离
class CarFactory:
def creat_car(self,brand):
if brand=="奔驰":
return benz()
elif brand=="宝马":
return BMW()
elif brand=="比亚迪":
return BYD()
class benz():
pass
class BMW():
pass
class BYD():
pass
c=CarFactory()
c1=c.creat_car("宝马")
c2=c.creat_car("比亚迪")
print(c1)
print(c2)
单例模式
确保一个类只有一个实例,且提供一个访问该实例的全局访问点,只生成一个实例对象。
class Mysingleton:
__obj=None
__init_flag=True
def __new__(cls, *args, **kwargs):
if cls.__obj==None:
cls.__obj=object.__new__(cls)
return cls.__obj
def __init__(self,name):
if
print("init....")
self.name=name
a=Mysingleton("aa")
b=Mysingleton("bb")
print(a)
print(b)