Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New snippet. "super" is true "super" and not restricted by the rules of python #305

Open
david-shiko opened this issue Jan 9, 2023 · 0 comments

Comments

@david-shiko
Copy link

We are all used to using:

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.

See: https://stackoverflow.com/a/45522873/11277611
Docs about super https://docs.python.org/3/library/functions.html#super

@david-shiko 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 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant