【笔记】Python3封装继承多态

前言

Python3封装继承多态学习笔记

继承

  • 子类默认能继承父类的所有属性和方法
  • 任何没有继承的类,默认都继承object类

单继承

  • 只继承一个父类
1
2
3
4
5
6
7
class Father(object):
def __init__(self, 属性名):
self.属性名 = 属性名
def 方法名():
...
class Son(Father):
...

多继承

  • 继承多个父类
  • 当一个类有多个父类时,默认使用第一个父类的同名属性和方法
1
2
3
4
5
6
class Father(object):
...
class Mother(object):
...
class Son(Father, Mother):
...

多级继承

1
2
3
4
5
6
class grandFather(object):
...
class Father(grandFather):
...
class Son(Father):
...

查看类的继承关系

1
print(类名.__mro__)

重写方法

  • 子类重写父类的同名方法
1
2
3
4
5
6
class Father(object):
def 同名方法():
...
class Son(Father):
def 同名方法():
...

子类调用父类

  • 子类调用父类的同名属性和方法

手动实现

  • 如果是先调用的父类的属性和方法,父类属性会覆盖子类属性,所以在调用属性之>前,先调用自己的子类的init魔法方法
  • 调用父类方法,为了保证调用到的也是父类的属性,所以必须在调用父类方法之前>先调用父类的init魔法方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Father(object):
def __init__(self):
...
def 同名方法():
...
class Son(Father):
def __init__(self):
self.__init__()
...
def 同名方法():
...
def 父类方法():
Father.__init__(self)
Father.同名方法(self)

super方法

  • 节省多继承得到的父类同名属性和方法的代码冗余
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Father(object):
def __init__(self):
...
def 同名函数():
...
class Son(Father):
def __init__(self):
self.__init__()
...
def 同名函数():
...
def 父类方法():
super(Son, self).__init__()
super(Son, self).同名函数()

省略参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Father(object):
def __init__(self):
...
def 同名函数():
...
class Son(Father):
def __init__(self):
self.__init__()
...
def 同名函数():
...
def 父类方法():
super().__init__()
super().同名函数()

封装

  • 私有权限能限制私有属性和私有方法不传递给子类

定义私有属性和方法

1
2
3
4
5
class 类名():
def __init__(self, 属性名):
self.__属性名 = 属性名
def __方法名():
...

获取和修改私有属性和方法

1
2
3
4
5
6
7
8
9
class 类名():
def __init__(self, 属性名):
self.__属性名 = 属性名
def __方法名():
...
def get_属性名(self):
return self.__属性名
def set_属性名(self, 属性值):
self.__属性名 = 属性值

多态

  • 多态是一种使用对象的方式,子类重写父类的方法,调用不同子类对象的相同父类方法,可以产生不同的执行结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Animal(object):
def 同名方法(self):
# 父类只作定义
pass
class Dog(Animal):
def 同名方法(self):
# 子类进行实现
...
class Cat(Animal):
def 同名方法(self):
# 子类进行实现
...

class 类名(object):
def 方法名(self, 参数名):
参数名.同名方法()

dog = Dog()
cat = Cat()
main = Main()

# 传入不同的对象,调用不通对象的同名方法
main.eat(dog)
main.eat(cat)

类属性

  • 类属性就是类对象所拥有的属性,它被该类的所有实例对象所共有
  • 类属性可以使用类对象或实例对象访问
1
2
3
4
5
6
class 类名():
属性名 = 属性值

对象名 = 类名()
print(对象名.属性名)
print(类名.属性名)

类属性的修改

  • 如果用类直接访问类属性进行修改,则进行了全局修改,其他对象访问到的数据会同步
  • 如果用对象访问类属性进行修改,则进行了局部修改,相当于创建了与类属性同名的实例属性,其他对象和类中的数据都不会同步

类方法

  • 类中通过装饰器@classmethod标识的方法为类方法,对于类方法,第一个参数必须是类对象,一般以cls作为第一个参数
  • 当方法中需要使用类对象时(如访问类属性)需要定义类方法
  • 类方法一般和类属性配合使用
1
2
3
4
5
6
7
8
9
10
11
class 类名():

__属性名 = 属性值

@classmethod
def get_属性名(cls):
return cls.__属性名

@classmethod
def set_属性名(cls, 参数):
cls.__属性名 = 参数

静态方法

  • 静态方法需要通过@staticmethod来进行修饰

  • 静态方法既不需要传递类对象,也不需要传递实例对象

  • 静态方法也能通过类对象和实例对象去访问

  • 当方法中既不需要使用实例对象,也不需要使用类对象时,通常定义静态方法,用于取消不需要的参数传递,减少不必要的内存占用和性能消耗

1
2
3
4
class 类名():
@staticmethod
def 方法名():
...

完成

参考文献

哔哩哔哩——Python-清风