Inheritance - how super() should be used

I was wondering what is the difference between:

20 class Person(object):
22 def __init__(self, name):
24 = name
27 = None
class Employee(Person):
32 def __init__(self, name, salary):
34 super(Employee, self).__init__(name)     <---------------This statement vs super().__init__(name)?
36 self.salary = salary

super searches the whole ancestor tree for the attribute you’re requesting, but it will stop at the first suitable find by default. If you provide a starting point for the search, it’ll start there and ignore previous finds.

class A(object):
    def func(self):
        print("func A")

class B(A):
    def func(self):
        print("func B")

class C(B):                    # method resolution order (MRO): C -> B -> A
    def func(self):
        super().func()         # prints func B (first find)
        super(C, self).func()  # is equivalent to super().func()
        super(B, self).func()  # prints func A (starts the search after class B)

Unless you have a sophisticated inheritance tree where multiple classes implement different versions of the same method, super() should suffice.

More info: Python docs, essay by R. Hettinger with good examples

thanks so much! I learned alot just now breaking the code. I was trying to use an if statement to create an object. I figured out a way to handled the exception. Im sure there is a better way but it will suffice for now. I was trying to set a variable self.type to point to a specific object id created. It worked until I used a subclass to access the parent’s type variable and it threw an exception that was difficult to handle bec I dont understand enough yet, but I learned alot. I know there are other libraries as well as built in function to deal that for efficiently. Like I said, itll take me time to learn all that. Is there a link that could brush me up on this specifically? If you can follow what I was trying to do? lol

Wow, awesome explanation. Didn’t know that you can set your starting point.

I’m afraid I didn’t quite follow. :smiley: Maybe post some code and the error message?

Thanks @DidierCH. :slight_smile:

Trust me you dont want to see how I butchered Python in that script lmao…I figured out what all I was doing wrong…thanks though

@florian I found some good videos on LInkedIn and Youtube