♣
题目部分(原文见公众号:python宝)
python宝:
https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzU5NjIyOTE4OQ==&scene=123#wechat_redirect
小麦苗DB宝:
https://mp.weixin.qq.com/mp/appmsgalbum?action=getalbum&__biz=MzIzOTA2NjEzNQ==&scene=1&album_id=1407409723808366593&count=3#wechat_redirect
小麦苗个人博客:https://www.xmmup.com/
Python 类的封装、继承、多态 3 大特性。继承机制经常用于创建和现有类功能类似的新类,又或是新类只需要在现有类基础上添加一些成员(属性和方法),但又不想直接将现有类代码复制给新类。也就是说,通过使用继承这种机制,可以轻松实现类的重复使用,减少代码冗余、提高重用性。
参考:https://www.w3school.com.cn/python/python_inheritance.asp
♣
答案部分
一、创建父类
任何类都可以是父类,因此语法与创建任何其他类相同:
实例
创建一个名为 Person 的类,其中包含 firstname 和 lastname 属性以及 printname 方法:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# 使用 Person 来创建对象,然后执行 printname 方法:
x = Person("fname1", "lname1")
print(x.printname()) # fname1 lname1
二、创建子类
要创建从其他类继承功能的类,请在创建子类时将父类作为参数发送:
实例
创建一个名为 Student 的类,它将从 Person 类继承属性和方法:
class Student(Person): # 现在,Student 类拥有与 Person 类相同的属性和方法。
pass
x = Student("fname2", "lname2") # 使用 Student 类创建一个对象,然后执行 printname 方法:
print(x.printname()) # fname2 lname2
三、添加 __init__() 函数
到目前为止,我们已经创建了一个子类,它继承了父类的属性和方法。
我们想要把 __init__()
函数添加到子类(而不是 pass
关键字)。
注释:每次使用类创建新对象时,都会自动调用 __init__() 函数。
实例
为 Student 类添加 __init__() 函数:
class Student(Person):
def __init__(self, fname, lname): # 添加属性等
'''
当您添加 __init__() 函数时,子类将不再继承父的 __init__() 函数。
注释:子的 __init__() 函数会覆盖对父的 __init__() 函数的继承。
如需保持父的 __init__() 函数的继承,请添加对父的 __init__() 函数的调用:
'''
# 在,我们已经成功添加了 __init__() 函数,并保留了父类的继承,我们准备好在 __init__() 函数中添加功能了。
Person.__init__(self, fname, lname)
s = Student("fname3", "lname3")
print(s.printname()) # fname3 lname3
四、super() 函数使用
super()
函数,它会使子类从其父继承所有方法和属性,通过使用 super()
函数,您不必使用父元素的名称,它将自动从其父元素继承方法和属性。
提示:如果您在子类中添加一个与父类中的函数同名的方法,则将覆盖父方法的继承。
class Child(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.today = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.today)
c = Child("fname4", "lname4", 2022)
print(c.welcome()) # Welcome fname4 lname4 to the class of 2022
五、Python的多继承
参考:https://www.jianshu.com/p/addd4a118e62
class Parent1:
def func1(self):
print("this is function 1")
class Parent2:
def func2(self):
print("this is function 2")
class Child(Parent1, Parent2):
def func3(self):
print("this is function 3")
ob = Child()
print(ob.func1()) # this is function 1
print(ob.func2()) # this is function 2
print(ob.func3()) # this is function 3
About Me:小麦粒
● 本文作者:小麦粒,专注于python、数据分析、数据挖掘、机器学习相关技术,也注重技术的运用
● 作者博客地址:https://blog.csdn.net/u010986753
● 本系列题目来源于作者的学习笔记,部分整理自网络,若有侵权或不当之处还请谅解
● 版权所有,欢迎分享本文,转载请保留出处
● 个人微信号:pythonbao 联系我加微信群
● 个人QQ:87605025
● QQ交流群py_data :483766429
● 公众号:python宝 或 DB宝
● 提供OCP、OCM和高可用最实用的技能培训
● 题目解答若有不当之处,还望各位朋友批评指正,共同进步
如果你觉得到文章对您有帮助,点击下方我的头像,赞赏我哦!
有您的支持,小麦粒一定会越来越好!