Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

What are Python function attributes?

I have the following code for a python function

def foo():
     pass

What are python function attributes?

How do I assign and retrieve attributes from this function?


1 Answer
Rajendra Dharmkar

Everything in Python is an object, and almost everything has attributes and methods. In python, functions too are objects. So they have attributes like other objects. All functions have a built-in attribute __doc__, which returns the doc string defined in the function source code. We can also assign new attributes to them, as well as retrieve the values of those attributes.

For handling attributes, Python provides us with “getattr” and “setattr”, a function that takes three arguments. There is no difference between “setattr” and using the dot-notation on the left side of the = assignment operator:

The given code can be written as follows to assign and retrieve attributes.

def foo():
    pass
setattr(foo, 'age', 23 )
setattr(foo, 'name', 'John Doe' )
print(getattr(foo, 'age'))
foo.gender ='male'
print(foo.gender)
print(foo.name)
print(foo.age)

OUTPUT

C:/Users/TutorialsPoint1/~.py
23
male
John Doe
23
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.