When writing the __init__
function for a class in python, you should always call the __init__
function of its superclass. We can use this to pass the relevant attributes directly to the superclass, so your code would look like this:
class Person(object):
def __init__(self, name, phone):
self.name = name
self.phone = phone
class Teenager(Person):
def __init__(self, name, phone, website):
Person.__init__(self, name, phone)
self.website=website
As others have pointed out, you could replace the line
Person.__init__(self, name, phone)
with
super(Teenager, self).__init__(name, phone)
and the code will do the same thing. This is because in python instance.method(args)
is just shorthand for Class.method(instance, args)
. If you want use super
you need to make sure that you specify object
as the base class for Person
as I have done in my code.
The python documentation has more information about how to use the super
keyword. The important thing in this case is that it tells python to look for the method __init__
in a superclass of self
that is not Teenager
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…