一、继承
1)封装:self参数传入的是创建的对象,self可以直接将对象带参数传入类中方法,这种在对象中封装数据,对类进行了优化的方法就叫封装。
2)当一个继承自另一个累的时候,会先去子类里面找,如果有先调用没有去夫类找。
1)
class Rectangle: # 矩形类
def __init__(self,length,width):
self.length = length
self.width = width
def area(self):
areas = self.length * self.width
return areas
lass Square(Rectangle): # 正方形类
pass
a = Square()
2)
class Rectangle:
def__init__(self, length, width)
self.length = length
self.width = width
def getarea(self):
area = self.length * self.width
print('面积为:%s‘% area)
class Square(Rectangle): # 正方形类
def __init__(self, length, width):
if length == width:
Rectangle.__init__(self, length, width)
else:
print(’不是正方形‘)
二、多继承
1)多继承用逗号隔开,从左往右继承 不想继承夫类可以重写之后被覆盖
1)class A:
pass
# def f(self):
# print("A")
class B:
def f(self):
print("B")
class C(A):
pass
# def f(self):
# print("C")
class D(B):
pass
# def f(self):
# print("D")
class E(C, D):多继承用逗号隔开,从左往右继承 不想继承夫类可以重写之后被覆盖
如果用夫类的方法则:
1.夫类.方法(self)
pass
# def f(self):
# print("E")
e = E() # 此时类中的self始终指向的是e,所有方法选择的优先级始终从E开始判断的
e.f() # E无--->C,C无--->A,A无--->D,D无--->B
2)class Animal:
def __init__(self):
print("A构造方法")
class Owner:
def __init__(self):
print("C构造方法")
class Cat(Owner, Animal):
def __init__(self):
print("B构造方法")
kitty = Cat()
class A:
# def run(self):
# print("happy")
#
#
# class D:
# def run(self):
# print("happy")
#
#
# class B:
# def eat(self):
# print("miaomiaomiao")
#
#
# class C(D, B):
# def run(self):
# D.run(self)
# print("fly")
#
#
# c = C()
# c.run()
class A(object):
def run(self):
print("happy")
class B:
def eat(self):
print("miaomiaomiao")
class C(A, B):
def run(self):
super().run() # super函数可以调用父类的方法,
print("fly")
c = C()
c.run()
print(C.mro()) # [<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]获取全部的继承关系
print(C.__bases__) # (<class '__main__.A'>, <class '__main__.B'>) 查看继承的全部父类
print(C.__base__) # <class '__main__.A'> 查看继承的第一个父类