python中super的应用以及实例代码
时间: 2023-03-27 13:03:06 浏览: 59
super() 是 Python 中的一个内置函数,它可以用来调用父类的方法。在子类中,如果需要调用父类的方法,可以使用 super() 函数来实现。下面是一个示例代码:
```
class Parent:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f"Hello, {self.name}!")
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
def say_hello(self):
super().say_hello()
print(f"I am {self.age} years old.")
child = Child("Tom", 10)
child.say_hello()
```
在这个示例代码中,我们定义了一个父类 Parent 和一个子类 Child。子类 Child 继承了父类 Parent,并且重写了父类的 say_hello() 方法。在子类中,我们使用 super() 函数来调用父类的构造函数和 say_hello() 方法。这样,我们就可以在子类中使用父类的方法,而不需要重复编写相同的代码。
相关问题
python中super的用法实例
super()函数用于调用父类的方法。它的语法如下:
```
super([type[, object-or-type]])
```
其中,type是子类,object-or-type是子类对象或类。使用super()函数时,如果没有指定参数,则默认使用当前类及对象。下面是super()函数的用法实例:
```python
class A:
def my_method(self):
print("A's method")
class B(A):
def my_method(self):
super().my_method()
print("B's method")
b = B()
b.my_method()
```
输出结果为:
```
A's method
B's method
```
在上面的例子中,子类B调用了父类A的my_method()方法,并在其后面添加了自己的方法。使用super()函数可以避免重复代码,提高代码的可维护性。
python中类的继承代码实例
以下是一个简单的Python类的继承代码实例:
```python
# 定义父类
class Member:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age)
# 定义子类,继承父类
class Student(Member):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def display(self):
super().display()
print("Grade:", self.grade)
# 创建子类对象并调用方法
student = Student("John", 18, 12)
student.display()
```
这个例子中,我们定义了一个父类`Member`,它有一个`__init__`方法和一个`display`方法。然后我们定义了一个子类`Student`,它继承了父类`Member`。子类`Student`有自己的`__init__`方法和`display`方法,并且通过`super()`函数调用了父类的`__init__`方法和`display`方法。最后,我们创建了一个`Student`对象并调用了`display`方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)