1. 直接使用父类的类名来直接调用父类的方法。
```python
class Parent:
def __init__(self):
print('This is parent init.')
def sleep(self):
print('Parent sleeps.')
class Child(Parent):
def __init__(self):
Parent.__init__(self) 直接调用父类的构造函数
print('This is child init.')
def sleep(self):
print('Child sleeps.')
c = Child()
c.sleep() 输出:Parent sleeps. Child sleeps.
2. 使用`super()`函数调用父类的方法。
```python
class Parent:
def __init__(self):
self.name = 'Parent'
def print_name(self):
print('Parent Class:', self.name)
class Child(Parent):
def __init__(self):
super().__init__() 调用父类的构造函数
self.name = 'Child'
def print_name(self):
super().print_name() 调用父类的打印方法
child = Child()
child.print_name() 输出:Parent Class: Parent Child Class: Child
3. 使用`super(type, obj).method(args)`方法调用,其中`type`是子类的类型,`obj`是子类的实例。
```python
class Parent:
def __init__(self):
self.name = 'Parent'
def print_name(self):
print('Parent Class:', self.name)
class Child(Parent):
def __init__(self):
super(Child, self).__init__() 使用super()调用父类的构造函数
self.name = 'Child'
def print_name(self):
super().print_name() 使用super()调用父类的打印方法
child = Child()
child.print_name() 输出:Parent Class: Parent Child Class: Child
4. 使用`super(子类名, self).父类方法名()`方法调用,其中`子类名`是子类的名称,`self`是子类的实例。
```python
class Parent:
def __init__(self):
self.name = 'Parent'
def print_name(self):
print('Parent Class:', self.name)
class Child(Parent):
def __init__(self):
super(Child, self).__init__() 使用super()调用父类的构造函数
self.name = 'Child'
def print_name(self):
super(Child, self).print_name() 使用super()调用父类的打印方法
child = Child()
child.print_name() 输出:Parent Class: Parent Child Class: Child
以上是Python中调用父类方法的几种常见方式。您可以根据需要选择合适的方法