继承是面向对象编程最重要的特征之一,它源于人们认识客观世界的过程,是自然界普遍存在的一种现象。
Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对象是很容易的。本章节我们将详细介绍Python的面向对象编程。
如果你以前没有接触过面向对象的编程语言,那你可能需要先了解一些面向对象语言的一些基本特征,在头脑里头形成一个基本的面向对象的概念,这样有助于你更容易的学习Python的面向对象编程。
接下来我们先来简单的了解下面向对象的一些基本特征
创建类
使用 class 语句来创建一个新类,class 之后为类的名称并以冒号结尾:
class ClassName:
'类的帮助信息' #类文档字符串
class_suite #类体
类的帮助信息可以通过ClassName.__doc__查看。
class_suite 由类成员,方法,数据属性组成。
如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法:
class Fruit:
color = "绿色"
def harvest(self,color):
print("水果是:"+color+"的!")
print("水果已经收获......")
print("水果原来是:"+Fruit.color+"的!")
class Orange(Fruit):
color = "黄色"
def __init__(self):
print("\n我是橘子")
def harvest(self,color):
print("橘子是:" + color + "的!")
print("橘子已经收获......")
print("橘子原来是:" + Fruit.color + "的!")
C:\Users\user\AppData\Local\Programs\Python\Python37-32\python.exe E:/pycharm/pythonworker/learn/oop.py
水果是:绿色的!
水果已经收获......
水果原来是:绿色的!
我是橘子
橘子是:黄色的!
橘子已经收获......
橘子原来是:绿色的!
在派生类中定义__init__()方法是,不会自动调用基类的__init__()方法。
class Fruit:
def __init__(self,color="绿色"):
Fruit.color = color
def harvest(self):
print("水果原来是:"+Fruit.color+"的!")
class Apple(Fruit):
def __init__(self):
# super().__init__()
print("\n我是苹果")
apple = Apple()
apple.harvest()
执行上面的代码后,将显示如图的异常信息。
C:\Users\user\AppData\Local\Programs\Python\Python37-32\python.exe E:/pycharm/pythonworker/learn/oop.py
我是苹果
Traceback (most recent call last):
File "E:/pycharm/pythonworker/learn/oop.py", line 20, in
apple.harvest()
File "E:/pycharm/pythonworker/learn/oop.py", line 12, in harvest
print("水果原来是:"+Fruit.color+"的!")
AttributeError: type object 'Fruit' has no attribute 'color'
因此,要在派生类中使用基类的__inti__()方法,必须要进行初始化,即需要在派生类中使用super()函数调用基类的__init__()方法。如下
class Fruit:
def __init__(self,color="绿色"):
Fruit.color = color
def harvest(self):
print("水果原来是:"+Fruit.color+"的!")
class Apple(Fruit):
def __init__(self):
super().__init__() # super().__init__() 方法调用基类__init__()方法
print("\n我是苹果")
apple = Apple()
apple.harvest()
执行结果:
C:\Users\user\AppData\Local\Programs\Python\Python37-32\python.exe E:/pycharm/pythonworker/learn/oop.py
我是苹果
水果原来是:绿色的!
引用: https://m.runoob.com/python/python-object.html 菜鸟教程