Python __init__ syntax

后端 未结 2 1078
囚心锁ツ
囚心锁ツ 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

提交回复
热议问题