class Foo:
pass
class Bar(Foo):
def __init__(self):
super().__init__()
But once, during coding, I just wondered, how does super know about the Bar parent class at all?
Does str().__some_method__ also know about the Bar class around?
Check this class
class SuperMystery:
def nothing_special(self):
print('__class__' in locals()) # False
def surprise(self):
super # senseless expression, do nothing
print('__class__' in locals()) # True
@staticmethod
def even_more(): # Just as function, no reference to an instance/class
super # Just a word, senseless expression , do nothing
print('__class__' in locals()) # True
super_mystery = SuperMystery()
super_mystery.nothing_special()
super_mystery.surprise()
super_mystery.even_more()
Curious? It's just a Python hack that violates regular rules!
Explanation:
When the Python compiler meets super in the method, it will insert some special attributes into the method and its namespace.
super will fool the compiler into creating a __class__ cell, even if it's senseless and does nothing.
We are all used to using:
But once, during coding, I just wondered, how does
super
know about theBar
parent class at all? Doesstr().__some_method__
also know about theBar
class around?Check this class
Curious? It's just a Python hack that violates regular rules!
Explanation: When the Python compiler meets
super
in the method, it will insert some special attributes into the method and its namespace.super
will fool the compiler into creating a__class__
cell, even if it's senseless and does nothing.See: https://stackoverflow.com/a/45522873/11277611 Docs about
super
https://docs.python.org/3/library/functions.html#super