Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
What are Python function attributes?
Python is made up of objects but can also be used in other ways. Similarly, functions are also made up of objects, since they are objects they have attributes like identifier, title, inputs, outputs, etc.
The value of an attribute cannot be changed once it has been set. To set the value of an attribute we use a function setattr and to know what value has been set as the attribute we use a function getattr.
To access the attributes of a function we use the ?.? Operator. Some of the attributes have a special functionality such that they can be implemented directly at runtime instead of compile time. The function ?func_dict? can be used to know the attributes present in the function and their values.
Example 1
In the below program, we define an attribute directly in the function, and coming to another attribute, we are explicitly setting that attribute.
def function(): function.a = 14 print(function.a) function() function.name = "bar" print(function.__dict__)
Output
The output for the above python program is obtained as ?
14
{'a': 14, 'name': 'bar'}
Example 2
In the below program, we are defining an empty function and then adding attributes to that function manually. Then we are retrieving that attributes
def city(): pass setattr(city,'Name','Hyderabad') setattr(city,'State','Telangana') print(getattr(city, 'Name')) print(city.Name) print(city.State)
Output
The output of the following program is
Hyderabad Hyderabad Telangana
Example 3
In this program we defined a function and returned the values that were set
def employee(employee_id, employee_name, wage):
return f'Employee ID: {employee_id}\nEmployee Name: {employee_name}\nWage: {wage}'
print(employee('E69', 'Janardhan', 25000))
Output
The output of the following program is
Employee ID: E69 Employee Name: Janardhan Wage: 25000
Example 4
Let us see another example for this ?
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
The output of the following program is
23 male John Doe 23
