Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当代码仍在运行时,我是否需要在子类中始终使用init来实例化父类?_Python_Oop_Inheritance_Init_Super - Fatal编程技术网

Python 当代码仍在运行时,我是否需要在子类中始终使用init来实例化父类?

Python 当代码仍在运行时,我是否需要在子类中始终使用init来实例化父类?,python,oop,inheritance,init,super,Python,Oop,Inheritance,Init,Super,对于这个例子,我是否总是需要实例化父类,因为当我删除它时它仍然有效 class Person: def __init__(self, name): self.name = name @property def name(self): return self._name @name.setter def name(self, value): self._name = value class Su

对于这个例子,我是否总是需要实例化父类,因为当我删除它时它仍然有效

class Person:
    def __init__(self, name):
        self.name = name    

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value


class SubPerson(Person):

    # Do I need this an init call? If I remove this init call, it still runs
    def __init__(self, name):
        super().__init__(name)

    @property
    def name(self):
        return super().name 

    @name.setter
    def name(self, value):
        return super(SubPerson, SubPerson).name.__set__(self, value)


s = SubPerson("John") 
print(s.name) //John

谢谢大家!

绝对不是。典型的模式是,子级可能需要设置父级没有的额外字段,但如果您完全省略
\uuuu init\uuuu
方法,则它将从父级继承,这在您的情况下是正确的行为