Python类的继承和多态代码详解
作者:feesland 时间:2022-01-20 14:16:39
Python类的继承
在OOP(ObjectOrientedProgramming)程序设计中,当我们定义一个class的时候,可以从某个现有的class继承,新的class称为子类(Subclass),而被继承的class称为基类、父类或超类(Baseclass、Superclass)。
我们先来定义一个classPerson,表示人,定义属性变量name及sex(姓名和性别);
定义一个方法print_title():当sex是male时,printman;当sex是female时,printwoman。参考如下代码:
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
def print_title(self):
if self.sex == "male":
print("man")
elif self.sex == "female":
print("woman")
class Child(Person): # Child 继承 Person
pass
May = Child("May","female")
Peter = Person("Peter","male")
print(May.name,May.sex,Peter.name,Peter.sex) # 子类继承父类方法及属性
May.print_title()
Peter.print_title()
而我们编写Child类,完全可以继承Person类(Child就是Person);使用classsubclass_name(baseclass_name)来表示继承;
继承有什么好处?最大的好处是子类获得了父类的全部属性及功能。如下Child类就可以直接使用父类的print_title()方法
实例化Child的时候,子类继承了父类的构造函数,就需要提供父类Person要求的两个属性变量name及sex:
在继承关系中,如果一个实例的数据类型是某个子类,那它也可以被看做是父类(May既是Child又是Person)。但是,反过来就不行(Peter仅是Person,而不是Child)。
继承还可以一级一级地继承下来,就好比从爷爷到爸爸、再到儿子这样的关系。而任何类,最终都可以追溯到根类object,这些继承关系看上去就像一颗倒着的树。比如如下的继承树:
isinstance()及issubclass()
Python与其他语言不同点在于,当我们定义一个class的时候,我们实际上就定义了一种数据类型。我们定义的数据类型和Python自带的数据类型,比如str、list、dict没什么两样。
Python有两个判断继承的函数:isinstance()用于检查实例类型;issubclass()用于检查类继承。参见下方示例:
class Person(object):
pass
class Child(Person): # Child 继承 Person
pass
May = Child()
Peter = Person()
print(isinstance(May,Child)) # True
print(isinstance(May,Person)) # True
print(isinstance(Peter,Child)) # False
print(isinstance(Peter,Person)) # True
print(issubclass(Child,Person)) # True
Python类的多态
在说明多态是什么之前,我们在Child类中重写print_title()方法:若为male,printboy;若为female,printgirl
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
def print_title(self):
if self.sex == "male":
print("man")
elif self.sex == "female":
print("woman")
class Child(Person): # Child 继承 Person
def print_title(self):
if self.sex == "male":
print("boy")
elif self.sex == "female":
print("girl")
May = Child("May","female")
Peter = Person("Peter","male")
print(May.name,May.sex,Peter.name,Peter.sex)
May.print_title()
Peter.print_title()
当子类和父类都存在相同的print_title()方法时,子类的print_title()覆盖了父类的print_title(),在代码运行时,会调用子类的print_title()
这样,我们就获得了继承的另一个好处:多态。
多态的好处就是,当我们需要传入更多的子类,例如新增Teenagers、Grownups等时,我们只需要继承Person类型就可以了,而print_title()方法既可以直不重写(即使用Person的),也可以重写一个特有的。这就是多态的意思。调用方只管调用,不管细节,而当我们新增一种Person的子类时,只要确保新方法编写正确,而不用管原来的代码。这就是著名的“开闭”原则:
对扩展开放(Openforextension):允许子类重写方法函数
对修改封闭(Closedformodification):不重写,直接继承父类方法函数
子类重写构造函数
子类可以没有构造函数,表示同父类构造一致;子类也可重写构造函数;现在,我们需要在子类Child中新增两个属性变量:mother和father,我们可以构造如下(建议子类调用父类的构造方法,参见后续代码):
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
class Child(Person): # Child 继承 Person
def __init__(self,name,sex,mother,father):
self.name = name
self.sex = sex
self.mother = mother
self.father = father
May = Child("May","female","April","June")
print(May.name,May.sex,May.mother,May.father)
Person
若父类构造函数包含很多属性,子类仅需新增1、2个,会有不少冗余的代码,这边,子类可对父类的构造方法进行调用,参考如下:
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
class Child(Person): # Child 继承 Person
def __init__(self,name,sex,mother,father):
Person.__init__(self,name,sex) # 子类对父类的构造方法的调用
self.mother = mother
self.father = father
May = Child("May","female","April","June")
print(May.name,May.sex,May.mother,May.father)
多重继承
多重继承的概念应该比较好理解,比如现在需要新建一个类baby继承Child,可继承父类及父类上层类的属性及方法,优先使用层类近的方法,代码参考如下:
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
def print_title(self):
if self.sex == "male":
print("man")
elif self.sex == "female":
print("woman")
class Child(Person):
pass
class Baby(Child):
pass
May = Baby("May","female") # 继承上上层父类的属性
print(May.name,May.sex)
May.print_title() # 可使用上上层父类的方法
class Child(Person):
def print_title(self):
if self.sex == "male":
print("boy")
elif self.sex == "female":
print("girl")
class Baby(Child):
pass
May = Baby("May","female")
May.print_title() # 优先使用上层类的方法
来源:http://www.cnblogs.com/feeland/p/4419121.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python合并多个装饰器小技巧
Pycharm最全报错的原因与解决方法总结(推荐!)
![](https://img.aspxhome.com/file/2023/4/79534_0s.jpg)
ORACLE数据库空间整理心得
详解使用vscode+es6写nodejs服务端调试配置
Python基于最小二乘法实现曲线拟合示例
![](https://img.aspxhome.com/file/2023/8/67348_0s.png)
oracle执行cmd的实现方法
ASP连接MySQL数据库代码示例
php实现压缩多个CSS与JS文件的方法
sql自动增长标识导致导入数据问题的解决方法
SQL Server 中导入导出数据三方法比较
Python使用Beautiful Soup实现解析网页
CSS实例教程:复合型CSS条状图表(下)
IE里模拟DOMContentLoaded事件
PHP fprintf()函数用法讲解
![](https://img.aspxhome.com/file/2023/8/55388_0s.png)
python使用wxpy实现微信消息防撤回脚本
在python中利用GDAL对tif文件进行读写的方法
XHTML1.0规范:您是否为img图片标签赋予alt属性
![](https://img.aspxhome.com/file/UploadPic/20099/21/2009921111528400s.gif)
很快大多数网民将放弃IE浏览器
![](https://img.aspxhome.com/file/UploadPic/20092/5/browsersfeb09-86s.jpg)