In python OOP, lets say, Person is a parent class with its own initialiser; then Student is a sub class of Person, before I use Student, must Person.__init__(self)
be called first in the initialiser of Student? Plus, can I define a new initialiser in Student class?
class Person():
def __init__(self):
Above is class Person with its initialiser
class Student(Person):
def __init__(self):
Person.__init__(self)
def __init__(self, age)
What I mean is, could Student have its own initialiser? If so, must Person.__init__(self)
be called in the Student initialiser in this case?
Of course, Student
can have its own initialiser. However, a class can only have one initialiser in Python, because that is a special method called within the constructor (the class __new__
method).
So when we say a sub class has its own initialiser, we really mean something like this:
class Worker(People):
def __init__(self, company):
self.company = company
As @IanH pointed out, you don't have to call the super class initialiser. And when you think you should call it (probably for some common initialization), you can do it like this:
class People:
def __init__(self, name):
self.name = name
class Student(People):
def __init__(self, name, school):
super(Student, self).__init__(name)
self.school = school
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With