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)
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:
- 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.
- 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.