简体   繁体   中英

Arguments to __init__ when using a subclass and super

I'm spending a nice Saturday looking a bit deeper into Python objects, and had a simple question that isn't mindblowing but kinda curious.

Say I have a base class and a subclass as follows :

class Person:

    def __init__(self, first, last):
        self.firstname = first
        self.lastname = last

    def __str__(self):
        return self.firstname + " " + self.lastname

class Employee(Person):

    def __init__(self, first, last, staffnum):
        super().__init__(first, last)
        self.staffnumber = staffnum


x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson", "1007")

I'm looking at the Employee class.

Given:
we are using super() and it has arguments in it,
why in python does the __init__ still require us to type first, last ?
Shouldn't this be inferred from our use of super? Seems like extra repetitive typing. What's the reasoning for the author having to do this?

The reason is so you can further customize subclasses. In your example, when you still want to input first and last it is more of a hassle because you have to type it twice, like this:

class Employee(Person):
    def __init__(self, first, last):
        super().__init__(first, last)

emp1 = Employee("Bob", "Jones")

However, you might want to autofill some of those values. In this example maybe a FamilyMember class where the last name is common.

class FamilyMember(Person):
    def __init__(self, first):
        super().__init__(first, last="Erikson")

fm1 = FamilyMember("Paul")

In this case you would only need to input the first variable for a FamilyMember and the last variable would be automatically filled in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM