- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Environmental Science
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- articles and Answers
- Effective Resume Writing
- HR Interview articles
- Computer Glossary
- Who is Who
What are Python function attributes?
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.
Example
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/codegyan/~.py 23 male John Doe 23
Advertisements
ads