There is no generic way for a function to refer to itself. Consider using a decorator instead. If all you want as you indicated was to print information about the function that can be done easily with a decorator:

from functools import wraps
def showinfo(f):
    @wraps(f)
    def wrapper(*args, **kwds):
         print(f.__name__, f.__hash__)
         return f(*args, **kwds)
    return wrapper

@showinfo
def aa():
    pass

If you really do need to reference the function, then just add it to the function arguments:

def withself(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        return f(f, *args, **kwds)
    return wrapper

@withself
def aa(self):
      print(self.__name__)
      # etc.

Edit to add alternate decorator:

You can also write a simpler (and probably faster) decorator that will make the wrapped function work correctly with Python's introspection:

def bind(f):
    """Decorate function `f` to pass a reference to the function
    as the first argument"""
    return f.__get__(f, type(f))

@bind
def foo(self, x):
    "This is a bound function!"
    print(self, x)


>>> foo(42)
<function foo at 0x02A46030> 42
>>> help(foo)
Help on method foo in module __main__:

foo(self, x) method of builtins.function instance
    This is a bound function!

This leverages Python's descriptor protocol: functions have a __get__ method that is used to create bound methods. The decorator simply uses the existing method to make the function a bound method of itself. It will only work for standalone functions, if you wanted a method to be able to reference itself you would have to do something more like the original solution.

Answer from Duncan on Stack Overflow
🌐
Baruchel
baruchel.github.io › blog › python › 2015 › 07 › 16 › self-reference-in-python
Self Reference in Python
I made it work on several versions of Python (versions 2 and 3 with CPython as well as with Pypy). import sys class _self_reference(): def __call__(self, *args): f = lambda *a: None f.__code__ = sys._getframe(1).f_code return f(*args) def __getitem__(self,n): def func(*args): f = lambda *a: None f.__code__ = sys._getframe(n+1).f_code return f(*args) return func self = _self_reference() Of course the self variable can be renamed like this or even simply _. The self function now calls the function called previously with new arguments.
Top answer
1 of 4
37

There is no generic way for a function to refer to itself. Consider using a decorator instead. If all you want as you indicated was to print information about the function that can be done easily with a decorator:

from functools import wraps
def showinfo(f):
    @wraps(f)
    def wrapper(*args, **kwds):
         print(f.__name__, f.__hash__)
         return f(*args, **kwds)
    return wrapper

@showinfo
def aa():
    pass

If you really do need to reference the function, then just add it to the function arguments:

def withself(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        return f(f, *args, **kwds)
    return wrapper

@withself
def aa(self):
      print(self.__name__)
      # etc.

Edit to add alternate decorator:

You can also write a simpler (and probably faster) decorator that will make the wrapped function work correctly with Python's introspection:

def bind(f):
    """Decorate function `f` to pass a reference to the function
    as the first argument"""
    return f.__get__(f, type(f))

@bind
def foo(self, x):
    "This is a bound function!"
    print(self, x)


>>> foo(42)
<function foo at 0x02A46030> 42
>>> help(foo)
Help on method foo in module __main__:

foo(self, x) method of builtins.function instance
    This is a bound function!

This leverages Python's descriptor protocol: functions have a __get__ method that is used to create bound methods. The decorator simply uses the existing method to make the function a bound method of itself. It will only work for standalone functions, if you wanted a method to be able to reference itself you would have to do something more like the original solution.

2 of 4
20

http://docs.python.org/library/inspect.html looks promising:

import inspect
def foo():
     felf = globals()[inspect.getframeinfo(inspect.currentframe()).function]
     print felf.__name__, felf.__doc__

you can also use the sys module to get the name of the current function:

import sys
def bar():
     felf = globals()[sys._getframe().f_code.co_name]
     print felf.__name__, felf.__doc__
Discussions

[Python] Can functions be self-referential?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
30
34
December 28, 2023
Self referential value
I have in my program “x” and “id(x)” I was wondering how to make them equal with each other. I’ve tried many things: is, and, eq, union(), intersection(), == And it checks whether it can do it and says no, they have no shared reference… Is there a way to force an equality on seemingly ... More on discuss.python.org
🌐 discuss.python.org
14
1
November 18, 2020
How does “self” in a class work?
What made the concept of self click for me, and this is completely ridiculous so you very well may get no miles out of this, but I treat building a class like building a Frankenstein monster. Attributes are physical features, methods are actions the monster can take, but "self" is what makes the monster alive, and thus self is the monster's (object's) "soul". That is, self is what made that particular monster (object) unique amongst other similar monsters (objects). I want to attack the village that is being mean about my sick experiments, and to really put a point on my powers, I also want to kidnap a villager. You know, evil scientist things. Since each monster has a soul, they can do independent things since the soul (self) makes them unique. Class Monster: def __init__(soul, name): soul.name = name def attack_village(): def kidnap_villager(): Now we "give life" to the monsters my instantiating (putting them on the table that lightning hits) two unique instances of the class: pat = Monster(pat) cris = Monster(cris) Despite being the "same" monster (same features, same look, same actions they can take), Pat and Cris can do things independently of the other. So I send Pat to kidnap a villager, and Cris to attack the village. pat.kidnap_villager() cris.attack_village() TL;DR: "self" is what makes each instance of a Class object unique. More on reddit.com
🌐 r/learnpython
70
262
December 22, 2021
object oriented - Why do you need "self." in Python to refer to instance variables? - Software Engineering Stack Exchange
Now, the issue is I often forget to write self as the first parameter in the function definitions in Python same is with calling methods on the same object. That said, I am quite amazed by this approach of Python. Basically we have to type more to get the things done, in the languages like Java and Ruby things are made simple by automatically referencing ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 20, 2015
🌐
W3Schools
w3schools.com › python › gloss_python_self.asp
Python Self
Python Examples Python Compiler ... Q&A Python Training ... The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
🌐
Reddit
reddit.com › r/learnprogramming › [python] can functions be self-referential?
r/learnprogramming on Reddit: [Python] Can functions be self-referential?
December 28, 2023 -

Example:

def function(x):
    stuff that works on x and produces y
    if condition:
        function(y)

My code goes through a bunch of calculations for an item and then does those same calculations for the ingredients needed to make that item. And on and on down the chain until it reaches the base ingredients which have no recipe and won't call the function again.

Edit: Oh and by the way, I don't know if "self-referential" means something else in the coding world. I just made that term up. So I'm sorry if there's any confusion.

🌐
Cs61a
cs61a.org › study-guide › self-reference
Study Guide: Self-Reference | CS 61A Summer 2026
Why can't we implement the logic of the whole function just in print_highest without the inner function? Here we see the beauty of self-reference: our function can remember what the previous highest number it has seen is, because we're storing that value in the parameter of the parent function print_highest.
🌐
GeeksforGeeks
geeksforgeeks.org › self-in-python-class
self in Python class - GeeksforGeeks
February 26, 2025 - In Python, the super() function is used to refer to the parent class or superclass.
🌐
Programiz
programiz.com › article › python-self-why
self in Python, Demystified
This is the reason the first parameter of a function in class must be the object itself. Writing this parameter as self is merely a convention. It is not a keyword and has no special meaning in Python. We could use other names (like this) but it is highly discouraged.
Find elsewhere
🌐
Python.org
discuss.python.org › python help
Self referential value - Python Help - Discussions on Python.org
November 18, 2020 - I have in my program “x” and “id(x)” I was wondering how to make them equal with each other. I’ve tried many things: is, and, eq, union(), intersection(), == And it checks whether it can do it and says no, they have n…
🌐
Reddit
reddit.com › r/learnpython › how does “self” in a class work?
r/learnpython on Reddit: How does “self” in a class work?
December 22, 2021 -

You have to add “self” as an argument to a class method. Why this specific syntax and how does it get interpreted? Is this because it inherits from the Python object model?

Is there any language where public methods do not contain “self” as an argument?

Thank you

🌐
GeeksforGeeks
geeksforgeeks.org › python › self-in-python-class
self in Python - GeeksforGeeks
July 4, 2026 - When ferrari.show() is called, self refers to ferrari. This allows each object to work with its own data. Yes, self is not a Python keyword. It is simply a naming convention that Python developers follow to represent the current object.
🌐
Edureka
edureka.co › blog › self-in-python
Self in Python Class | What is the Use of Python Self?
December 5, 2024 - Calling a Method: This also applies ... passing my_car in this example: my_car.start(). Assigning to self: The function takes the object as its self parameter....
🌐
Python
pythonprogramminglanguage.com › python-self
Understanding self in Python - Python
It’s a reference to the the object. The reason you need to use self. is because Python uses this to refer to instance attributes.
Top answer
1 of 3
31

1) Why is self required as an explicit parameter in method signatures?

Because methods are functions and foo.bar(baz) is just syntactic sugar for bar(foo, baz). Classes are just dictionaries where some of the values are functions. (Constructors are also just functions, which is why Python doesn't need new) You can say that Python makes it explicit that objects are built from simpler components. This is in accordance with the "explicit is better than implicit"-philosophy.

In contrast, in Java objects really are magic and cannot be reduced to simpler components in the language. In Java (at least until Java 8) a function is always a method owned by an object, and this ownership cannot be changed due to the static nature of the language. Therefore there is no ambiguity about what this refers to, so it makes sense to have it implicitly defined.

JavaScript is an example of a language that has an implicit this like Java, but where functions can exist separately from objects like in Python. This leads to a lot of confusion about what this refers to when functions are passed around and called in different contexts. Many instinctively think this must refer to some intrinsic property of the function, while it is actually purely determined by the way the function is called. I believe having this as an explicit parameter like in Python would make this much less confusing.

Some other benefits of the explicit self-parameter:

  • Decorators are just functions which wrap other functions. Since methods are just functions, decorators work just as fine on methods. If there were some kind of implicit self, decorators would not work transparently on methods.

  • Classmethods and static methods do not take an instance parameter. Classmethods take a class as the first argument (typically called cls). The explicit self or cls parameters make it much clearer what is going on, and what you have access to in the method.

2) Why must instance variables always be qualified with"self.?

In Java, you don't need to prefix member variables with "this.", but in Python "self." is always required. The reason is that Python does not have an explicit syntax for declaring variables, so there would be no way to tell if x = 7 is supposed to declare a new local variable or assign to a member variable. Specifying self. solves this ambiguity.

2 of 3
9

There is a rather simple reason that AFAIK hasn't really been touched upon in the cross-site duplicate, nor here: Python started out as a procedural language. It was based on ABC, also a procedural language.

Object-Orientation was added later, and when it was added, Guido van Rossum wanted to add the minimal amount of features possible, in order to keep the design of Python simple. Python already had dicts and functions, so why add something entirely new to the language, when an object can simply be a dict of slots and a class can simply be a dict of functions? A method can be interpreted as a partially-applied function that closes over a single distinguished argument. And that's precisely how methods are implemented in Python: they aren't. They are just functions which receive an extra distinguished argument.

🌐
CodingNomads
codingnomads.com › what-is-python-self
What is Python Self
A short rule-of-thumb answer to ... are functions that are part of a class. ... Instance methods take the instance of the object that they are part of as their first argument through the self parameter · The reference to the instance object gets passed implicitly when calling the method on the instance. Interested in becoming a professional Python ...
🌐
Scaler
scaler.com › home › topics › self in python class
Self in Python Class - How to Use Self in Python? | Scaler Topics
February 9, 2024 - The self is passed as an argument in the method of the class, and by default, it is compulsory to pass the reference of the class in all the methods of the class. ... In the above program, we pass the self in the method and access the class instance variable, i.e., a. Python doesn’t provide ...
🌐
Yasoob Khalid
yasoob.me › 2013 › 08 › 07 › the-self-variable-in-python-explained
The self variable in python explained - Yasoob Khalid
August 6, 2013 - Now x is a Restaurant which has a property bankrupt and a function open_branch. Now we can access the property bankrupt by typing: ... Now you can see that self refers to the bound variable or object. In the first case it was x because we had assigned the Restaurant class to x whereas in the second case it referred to Restaurant().