Friday, November 15, 2024
Google search engine
HomeLanguagesFunction aliasing in Python

Function aliasing in Python

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments