介绍

与java一样Python是一种支持面向对象编程的高级编程语言,它的核心思想之一就是继承、封装和多态。这三个概念是面向对象编程中最基本、最核心的思想之一,也是Python编程中必须掌握的知识点之一

继承

在面向对象编程中,继承是指一个类(称为子类)从另一个类(称为父类)继承其属性和方法。子类可以继承父类的所有属性和方法,并可以根据需要添加新的属性和方法。继承可以减少代码重复,提高代码的复用性和可维护性。

在python中是可以多继承的

案例
class IDictService:
    def getInfoById(self, i):
        print('需要子类实现')


class Log:

    def info(self, msg):
        print('[info]: %s' % msg)


class DictServiceImpl(IDictService, Log):
    def getInfoById(self, i):
        super().getInfoById(i)
        return i


dict = DictServiceImpl()

dict.info(dict.getInfoById(123))

# 通过该方法可以查看继承的类与顺序
print(DictServiceImpl.__mro__)

运行结果

需要子类实现
[info]: 123
(<class '__main__.DictServiceImpl'>, <class '__main__.IDictService'>, <class '__main__.Log'>, <class 'object'>)

封装

封装是面向对象编程中的一个重要概念,它允许我们将属性和方法绑定在一起,并将其隐藏在对象内部。通过这种方式,我们可以防止外部程序直接访问和修改对象的属性,从而保护对象的完整性和安全性。

在python中私有方法和属性通过两个下划线表示__

案例
class Person:
    def __init__(self):
        self.__age = 10
        self.name = 'wendell'

    def getAge(self):
        return self.__age

    def __print(self):
        print("-----test--------")


p = Person()
print(p.name)
print(p.getAge())

# 私有属性也是不安全的,只不过是加了个类前缀做了隐藏
p._Person__age = 20
print("被修改了", p.getAge())

# 不可以访问
# AttributeError: 'Person' object has no attribute 'age'
print(p.__age)
# AttributeError: 'Person' object has no attribute '__print'
print(p.__print())

运行结果

wendell
10
被修改了 20
Traceback (most recent call last):
  File "/Users/wendell/PycharmProjects/study/oop/class_private.py", line 23, in <module>
    print(p.age)
AttributeError: 'Person' object has no attribute '__age'

从上面的结果可以看出加了__后,对象里面就不会有这个属性了,python里面是通过加了个类前缀做了隐藏,从而实现私有属性的,但是不建议这么去访问
如p._Person__age

多态

多态允许我们使用相同的接口来操作不同的对象。通过这种方式,我们可以编写通用的代码,可以处理多种不同类型的对象,从而使代码更加灵活、可重用和可扩展。

案例
# 多态
class Dog:

    def color(self):
        print("默认颜色")


class RedDog(Dog):

    def color(self):
        print('红色dog')


class YellowDog(Dog):

    def color(self):
        print('黄色dog')


class Unknow(Dog):
    pass


yellow = YellowDog()
red = RedDog()
unknow = Unknow()


def print_color(dog):
    dog.color()


print_color(yellow)
print_color(red)
print_color(unknow)

执行结果

黄色dog
红色dog
默认颜色

上面案例中的 print_color 方法接受一个参数,这个参数没有定义死,而是随着运行时传入的不同对象而执行对应的方法。这就是多态,通过多态,我们可以编写通用的代码,可以处理多种不同类型的对象

总结

总之掌握面向对象这三个概念,我们可以编写更加优雅、健壮和可维护的Python代码。