The Wayback Machine - http://web.archive.org/web/20240118172258/https://www.geeksforgeeks.org/function-aliasing-in-python/
Open In App
Related Articles

Function aliasing in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In Python, we can give another name of the function. For the existing function, we can give another name, which is nothing but function aliasing.

Function aliasing in Python

In function aliasing, we create a new variable and assign the function reference to one existing function to the variable. We can verify that both the objects pointing to the same memory location using id() built-in function in Python.

Example 1: Basic usage of function aliasing in Python

Python3




def fun(name):
    print(f"Hello {name}, welcome to GeeksForGeeks!!!")
 
 
cheer = fun
print(f'The id of fun() : {id(fun)}')
print(f'The id of cheer() : {id(cheer)}')
 
fun('Geeks')
cheer('Geeks')


Output:

The id of fun() : 140716797521432
The id of cheer() : 140716797521432
Hello Geeks, welcome to GeeksForGeeks!!!
Hello Geeks, welcome to GeeksForGeeks!!!

Explanation: In the above example, only one function is available, but we can call that function by using either fun or cheer name.

Example 2: Function aliasing of custom objects

Here, we have defined a class Test and a method name() to return the u_name attribute of the class. Here, we are demonstrating the usage of function aliasing on the name() method of the test object.

Python3




class Test:
    def __init__(self):
        self.u_name = "user-origin"
 
    def name(self):
        return self.u_name
 
 
# create object of Test class
test = Test()
 
# create function reference and it's alias
name_fn = test.name
name_fn_ref = name_fn
 
# this will print user-origin
print(name_fn())
 
test.u_name = "user-mod"
 
# this will print user-mod
print(name_fn_ref())


Output:

user-origin
user-mod

Explanation: name_fn is the function reference to the name() method of the test object. name_fn_ref is the function alias of the function name_fn. After changing the attribute value of u_name the function alias also reflects the change that establishes the fact that, name_fn and name_dn_ref points to the same function.


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 21 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials