Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Inheritance Multiple Superclasses

Order of __init__ call? Can you guess which Init will be called first?

class Character:
    def __init__(self,name="",**kwargs):
        self.name = name
        print("In Character Class")

        for key,value in kwargs.items():
            setattr(self,key,value)

class Thief(Sneaky,Agile,Character):
    def pickpocket(self):
        return self.sneaky and bool(random.randint(0,1))

a = Thief(name = "Shivam", sneaky=False)

class Sneaky:
    sneaky = True
    def __init__(self,sneaky = True,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.sneaky = sneaky
        print("in Sneaky class")

    def hide(self,light_level):
        return self.sneaky and light_level <10

class Agile:
    agile = True

    def __init__(self, agile=True, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.agile = agile
        print("in Agile class")


    def evade(self):
        return self.agile and bool(random.randint(0,1))

mySelf = Thief(name = 'mySelf', sneaky = True)

1 Answer

Yup, Kenneth introduced briefly MRO but didn't get into how it works. However, when he introduced super(), in the Teacher's Notes section, there was a link to a blog post (https://rhettinger.wordpress.com/2011/05/26/super-considered-super/) that gave a brief rundown of how MRO works:

  1. subclasses precede superclasses So, since you've written Thief as a subclass of Sneaky, Agile, and Character, methods written into Thief that share the same name as methods in its parents will run first.
  2. where there is ambiguity, respect the order of the bases (order you wrote the parent classes in your definition of Thief) Since Sneaky, Agile, and Character are not subclasses of each other, there is some ambiguity. In this case, for methods with the same names across these classes, Python will follow the order you wrote when naming the parent classes for Thief. That is, mySelf will initialize in the order of Sneaky, Agile, and then Character.

Also, you don't have to guess or go through the rules to figure it out yourself! Kenneth previously mentioned the .mro attribute, which is builtin and tells you the order. You can run Thief.mro to find out the MRO for Thief.