About Python super()

Asked 2 years ago, Updated 2 years ago, 19 views

Create a class that inherits a class and create the initializer

def_init__(self):
    super().__init__()

Is there any point in saying thatI believe that the actions described here will be performed without any description at the point of succession. I look forward to hearing from you.

python

2022-09-30 14:28

1 Answers

Because you have overridden (overwritten) the parent class _init__, only the _init__ content defined in the child class is executed.Therefore, if you want to define the _init__ of the child class in the form of adding to the _init__ of the parent class, you must call the child class side _init__.

class Greet():
    def__init__(self):
        self.hello='Hello!'
    defenter(self):
        print(f'{self.hello}')

classGreet2 (Greet):
    def__init__(self):
        super().__init__()
        self.bye='Bye!'
    def department(self):
        print(f'{self.bye}')

dialogue = Greet2()
dialogue.enter()
dialogue.depart()

Comment out super().__init__() with this code

AttributeError: 'Greet2' object has no attribute 'hello'

This is because the override no longer runs the parent class _init__().


2022-09-30 14:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.