You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
The text was updated successfully, but these errors were encountered:
david-shiko
changed the title
New snippet. "super" are not restricted by rules of python
New snippet. "super" are not restricted by the rules of python
Jan 9, 2023
david-shiko
changed the title
New snippet. "super" are not restricted by the rules of python
New snippet. "super" is true "super" and not restricted by the rules of python
Jan 9, 2023
We are all used to using:
But once, during coding, I just wondered, how does
super
know about theBar
parent class at all?Does
str().__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#superThe text was updated successfully, but these errors were encountered: