首先让我们先复习一下昨天所学内容:
1.创建类:
class 类名():
类体(属性和方法)
2.创建对象:
引用(变量) = 类名()
init(self)构造函数
**3.方法:**类方法 对象方法
**4.面向对象的三大特性:**继承 封装 多态
继承: class 子类/派生类(父类/超类/基类)
class A():
def a():
pass
pass
class B(A):
def b():
pass
pass
class C(B):
pass
多继承:
class D(A,S,D)
def b()
pass
从左到右,整体深度优先,局部广度优先(有菱形结构)
覆盖/重写:父类中方法无法满足子类需求,可再重写一个将其覆盖.(方法名相同)
接下来我们说说一下多态:
多态:(多种形态) :继承-重写(子类覆盖父类方法)
没错,多态等同于重写/覆盖
class animal():
def eat(self):
print("eat")
class person(animal):
def eat(self):
print("rice")
class dog(animal):
def eat(self):
print("狗粮")
class cat(animal):
def eat(self):
print("猫粮")
p = person()
d = dog()
c = cat()
d.eat()
p.eat()
c.eat()
很简单,继续,说说类与类之间的关系:
类与类之间的关系:继承,关联(组合,聚合),依赖
关联:一个类的对象作为另一个类的属性。 好处:代码复用/减少代码冗余
现在有一个student类,类中有name属性和study方法;有一个teacher类,类中有stu属性和teach方法,而stu属性是由student类中的一个对象充当;这种关系我们称为关联关系。
class student():
def __init__(self,name):
self.name = name
def study(self):
print("我爱python")
class teacher():
def __init__(self,stu):
self.stu = stu
def teach(self):
print("教%spython"%self.stu.name)
st = student("lhy")
t = teacher(st)
t.teach()
并不难,再看依赖关系:
依赖:一个类的对象作为另一个类的方法参数。
class student():
def __init__(self,name):
self.name = name
def study(self):
print("我爱python")
class teacher():
def teach(self,stu):
print("教%spython"%stu.name)
s = student("lhy")
t = teacher()
t.teach(s)
我们开发项目时需要遵循一个原则,那就是高内聚低耦合,那我们就来排一下继承,关联,依赖的耦合程度(耦合程度越高关系越紧密):继承>关联>依赖。
(ps:根据具体业务具体分析)
接下来我们再补充一点:
类方法与对象方法,类属性与对象属性:
class A():
name = "lhy"#类属性
def __init__(self,age):
self.age = age#对象属性
@staticmethod
def a():
print("类方法中的静态方法")
def aa(self):
print("对象方法")
print(A.name)
A.a()
p = A(18)
print(p.age)
p.aa()