Creating Attributes

In Python a function is an object. Any object can have attributes that can be created using a dot operator. Function attributes are attached to the function as static variables. This is another alternative to global variables and it can be used to create encapsulated functions that behave like objects.

In the next example the function test_attr() is creating an attribute called counter the first time is called. Then the attribute is used to memorize the current counter value. Next time is able to return the value and increment it for next call.

Example:

# demonstrate attributes attached to a function
def test_attr():
    if not hasattr(test_attr, "counter"):
        test_attr.counter = 0
    else:
        test_attr.counter += 1
    return test_attr.counter


# call function  attributes
def main():
    for i in range(0,10):
        j=test_attr()
        print(i,'->',j)

# compiler entry point
if __name__ == "__main__":
    main()

Test output:

0 -> 0
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 5
6 -> 6
7 -> 7
8 -> 8
9 -> 9

Read next: Switch Simulation