Python Syntax __init__

While learning Python, I get some confusion about the syntax for initializing classes using inheritance. In various examples, I saw something like the following:

class Foo(Bar): def __init__(self, arg, parent = None): Bar.__init__(self, parent) self.Baz = arg etc. 

Although sometimes it's just

 class Foo(Bar): def __init__(self, arg): Bar.__init__(self) etc. 

When would you want to use "parent" as an argument to initialization functions? Thanks.

+3
source share
2 answers

Usually passing parent not required only if the constructor of the parent class explicitly needs such an argument. This is used in some hierarchies, such as PyQt.

And a good idiom for initializing a parent class is to use super :

 class Child(Father): def __init__(self): super(Child, self).__init__() 
+7
source

In your example, the variable "parent" is misleading. Just the parent class COULD requires additional arguments that must be provided

 class Pet: def __init__(self,name): self.name = name class Dog(Pet): def __init__(self,name,age): Pet.__init__(self,name) self.age = age 

In this example, the parent class Pet requires an attribute (name), and the child class provides it

As indicated, use the β€œsuper” syntax to invoke parent class methods

+2
source

Source: https://habr.com/ru/post/1444073/


All Articles