I’m Java person who just started learning Python. Take this example:
class Person():
def __init__(self, name, phone):
self.name = name
self.phone = phone
class Teenager(Person):
def __init__(self, name, phone, website):
self.name=name
self.phone=phone
self.website=website
I’m sure there’s a lot of redundant code (I know in Java, there are a lot of redundancies for the bit of code above).
Which parts are redundant with respect to which attributes are already inherited from the parent class?
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:As others have pointed out, you could replace the line
with
and the code will do the same thing. This is because in python
instance.method(args)is just shorthand forClass.method(instance, args). If you want usesuperyou need to make sure that you specifyobjectas the base class forPersonas I have done in my code.The python documentation has more information about how to use the
superkeyword. The important thing in this case is that it tells python to look for the method__init__in a superclass ofselfthat is notTeenager