电商网站开发意义,土建找工作去哪个网站,wordpress仿 模板,wordpress路径错误Python super
Python 的 super() 函数允许我们显式地引用父类。在继承的情况下#xff0c;当我们想要调用父类函数时#xff0c;它非常有用。
Python super 函数示例
首先#xff0c;让我们看一下我们在 Python 继承教程中使用的以下代码。在该示例代码中#xff0c;父类…Python super
Python 的 super() 函数允许我们显式地引用父类。在继承的情况下当我们想要调用父类函数时它非常有用。
Python super 函数示例
首先让我们看一下我们在 Python 继承教程中使用的以下代码。在该示例代码中父类是 Person子类是 Student。代码如下所示。
class Person:# 初始化变量name age 0# 定义构造函数def __init__(self, person_name, person_age):self.name person_nameself.age person_age# 定义类方法def show_name(self):print(self.name)def show_age(self):print(self.age)# 子类定义开始
class Student(Person):studentId def __init__(self, student_name, student_age, student_id):Person.__init__(self, student_name, student_age)self.studentId student_iddef get_id(self):return self.studentId # 返回学生 ID 的值# 子类定义结束# 创建父类对象
person1 Person(Richard, 23)
# 调用对象的成员方法
person1.show_age()
# 创建子类对象
student1 Student(Max, 22, 102)
print(student1.get_id())
student1.show_name()在上面的示例中我们调用了父类函数如下
Person.__init__(self, student_name, student_age) 我们可以用以下方式替换为 python super 函数调用。
super().__init__(student_name, student_age)输出在两种情况下都将保持不变如下图所示。
Python 3 super
请注意上述语法适用于 Python 3 的 super 函数。如果你使用的是 Python 2.x 版本则略有不同你需要做以下更改
class Person(object):
...super(Student, self).__init__(student_name, student_age)第一个更改是将 object 作为 Person 的基类。在 Python 2.x 版本中使用 super 函数是必需的。否则你将会收到以下错误。
Traceback (most recent call last):File super_example.py, line 40, in modulestudent1 Student(Max, 22, 102)File super_example.py, line 25, in __init__super(Student, self).__init__(student_name, student_age)
TypeError: must be type, not classobjsuper 函数本身的语法也有所改变。正如你所看到的Python 3 的 super 函数使用起来更加简单语法也更加清晰。
Python super 函数与多层继承
正如我们之前所述Python 的 super() 函数允许我们隐式地引用父类。但在多层继承的情况下它将引用哪个类呢好吧Python 的 super() 总是引用直接的父类。此外Python 的 super() 函数不仅可以引用 __init__() 函数还可以调用父类的所有其他函数。因此在下面的示例中我们将看到这一点。
class A:def __init__(self):print(Initializing: class A)def sub_method(self, b):print(Printing from class A:, b)class B(A):def __init__(self):print(Initializing: class B)super().__init__()def sub_method(self, b):print(Printing from class B:, b)super().sub_method(b 1)class C(B):def __init__(self):print(Initializing: class C)super().__init__()def sub_method(self, b):print(Printing from class C:, b)super().sub_method(b 1)if __name__ __main__:c C()c.sub_method(1)让我们看看上述 Python 3 多层继承的示例输出。
Initializing: class C
Initializing: class B
Initializing: class A
Printing from class C: 1
Printing from class B: 2
Printing from class A: 3因此从输出中我们可以清楚地看到首先调用了类 C 的 __init__() 函数然后是类 B最后是类 A。通过调用 sub_method() 函数也发生了类似的事情。
为什么我们需要 Python 的 super 函数
如果你之前有 Java 语言的经验那么你应该知道在那里也称为 super 对象的基类。因此这个概念对于程序员来说实际上是有用的。然而Python 也保留了使用超类名称来引用它们的功能。而且如果你的程序包含多层继承那么这个 super() 函数对你很有帮助。所以这就是关于 Python super 函数的全部内容。希望你理解了这个主题。如果有任何疑问请在评论框中提问。