Python __init__ syntax

后端 未结 2 1074
囚心锁ツ
囚心锁ツ 2021-02-14 13:42

While learning Python I\'m having some confusion over the syntax of the initialization of classes using inheritance. In various examples I\'ve seen something like the following

相关标签:
2条回答
  • 2021-02-14 13:59

    In your example the variable "parent" is misleading. Simply the parent class COULD require 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 pointed out, use "super" syntax to call parent classes methods

    0 讨论(0)
  • 2021-02-14 14:02

    Generally passing parent is not something that's required, only when the parent class's constructor explicitly needs such an argument. This is used in some hierarchies, such as PyQt.

    And a good idiom of parent class initialization is to use super:

    class Child(Father):
      def __init__(self):
        super(Child, self).__init__()
    
    0 讨论(0)
提交回复
热议问题