Python全系列 教程
3567个小节阅读:5931.1k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
继承是面向对象编程的三大特征之一。继承让我们更加容易实现类的扩展。实现代码的重用,不用再重新发明轮子(don’t reinvent wheels)。
如果一个新类继承自一个设计好的类,就直接具备了已有类的特征,就大大降低了工作难度。已有的类,我们称为“父类或者基类”,新的类,我们称为“子类或者派生类”。
Python支持多重继承,一个子类可以继承多个父类。继承的语法格式如下:
xxxxxxxxxx
class 子类类名(父类1[,父类2,...]):
类体
如果在类定义中没有指定父类,则默认父类是
object类
。也就是说,object
是所有类的父类,里面定义了一些所有类共有的默认实现,比如:__new__()
关于构造函数:
__init__
,实例化子类时,会自动调用父类定义的 __init__
。__init__
时,实例化子类,就不会调用父类已经定义的 __init__
__init__
时,要使用父类的构造方法,可以使用 super
关键字,也可以使用如下格式调用: 父类名.__init__(self, 参数列表)
xxxxxxxxxx
class Person:
def __init__(self,name,age):
print("Person的构造方法")
self.name = name
self.age = age
def say_age(self):
print(self.name,"的年龄是:",self.age)
class Student(Person):
def __init__(self,name,age,score):
# 子类并不会自动调用父类的__init__(),我们必须显式的调用它。
# Person.__init__(self, name, age)
# super(Student,self).__init__(name,age)
print("Student的构造方法")
# self.name = name
# self.age = age
self.score = score
s1 = Student("张三",15,85)
#s1.say_age()
print(dir(s1))
运行结果:
xxxxxxxxxx
张三 的年龄是: 15
['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'say_age', 'score']
实时效果反馈
1. 如下代码,说法错误的是:
xxxxxxxxxx
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def say_age(self):
print(self.name,"的年龄是:",self.age)
class Student(Person):
def __init__(self,name,age,score):
self.score = score
Person.__init__(self,name,age)
A Person
的父类是object
类
B Person
类没有父类
C Student
类的父类是Person
类,拥有name
、age
、score
属性
D Student
类的父类是Person
类,拥有say_age
方法
答案
1=>B