0
点赞
收藏
分享

微信扫一扫

在Python中,子类继承父类并调用父类的构造方法有几种方式: 1. 如果子类没有重写`__init__`,实例化子类时,会自动调用父类定义的`__init__`¹。 ```python clas

在Python中,子类继承父类并调用父类的构造方法有几种方式:


1. 如果子类没有重写`__init__`,实例化子类时,会自动调用父类定义的`__init__`¹。


```python

class Father(object):

   def __init__(self, name):

       self.name = name


class Son(Father):

   pass


son = Son('runoob')

```


2. 如果子类重写了`__init__`,实例化子类时,就不会调用父类已经定义的`__init__`¹。


```python

class Father(object):

   def __init__(self, name):

       self.name = name


class Son(Father):

   def __init__(self, name):

       print("hi")

       self.name = name


son = Son('runoob')

```


3. 如果子类重写了`__init__`并且想要继承父类的构造方法,可以使用`super`关键字¹。


```python

class Father(object):

   def __init__(self, name):

       self.name = name


class Son(Father):

   def __init__(self, name):

       super(Son, self).__init__(name)

       print("hi")

       self.name = name


son = Son('runoob')

```


4. 另一种经典写法是直接使用父类名称调用`__init__`¹。


```python

class Father(object):

   def __init__(self, name):

       self.name = name


class Son(Father):

   def __init__(self, name):

       Father.__init__(self, name)

       print("hi")

       self.name = name


son = Son('runoob')

```


以上就是Python中子类继承父类并调用父类构造方法的一些常见方式。希望对你有所帮助!


源: 与必应的对话, 2024/1/29

(1) Python 子类继承父类构造函数说明 | 菜鸟教程. https://www.runoob.com/w3cnote/python-extends-init.html.

(2) python调用父类方法的三种方式(super调用和父类名调用)_python子类调用父类方法-CSDN博客. https://blog.csdn.net/qdPython/article/details/130171271.

(3) python子类继承父类构造函数__init__的几种情况_python继承构造方法 __init__-CSDN博客. https://blog.csdn.net/weixin_40734030/article/details/122861895.

(4) python 子类如何调用父类的构造函数?(大牛实例代码详细教学) - 知乎专栏. https://zhuanlan.zhihu.com/p/113555723.

(5) Python类继承(调用父类成员与方法)-腾讯云开发者社区-腾讯云. https://cloud.tencent.com/developer/article/1827573.

举报

相关推荐

0 条评论