class attribute in python

Unlike other programming language like C++, Java – Python classes can hold data and behavior that is not part of an instance or object; instead they are part of the class. Python classes have attributes; these are referred to as class variables or attributes.

Python Class attributes are tied to the class rather than to any instance or objects.

For example, we have a class Account and a class attribute instance_count to keep a count of how many instances of the class are created:

class Account:
    """ An example class to hold a Account detail"""
    instance_count = 0

    def __init__(self, number):
        Account.instance_count += 1
        self.number = number

The variable instance_count is not part of an individual object, rather it is part of the class and all instances of the class can access that shared variable by prefixing it with the class name.

Now each time a new instance of the class is created, the instance_count is incremented, thus if we write:

acct1 = Account(123456)
acct2 = Account(234567)
acct3 = Account(345678)

print(Account.instance_count)

The output for above code snippet will be as below,

3

This is because 3 instances have been created and thus __init__() has been run 3 times and instance_count has been incremented three times.

Conclusion

In this article, we saw about declaring class attributes and its purpose in class.