Everything, almost everything in Python is an object. Every object has attributes and methods. Thus attributes are very fundamental in Python. A class is a construct which is a collection of similar objects. A class also has attributes. There will be a difference between the class attributes and instance attributes. The class attributes are shared by the instances of the class but it not true vice versa.
We can get a list of the attributes of an object using the built-in “dir” function. For example −
>>> s = 'abc' >>> len(dir(s)) 71 >>> dir(s)[:5] ['__add__', '__class__', '__contains__', '__delattr__', '__doc__'] >>> i = 123 >>> len(dir(i)) 64 >>> dir(i)[:5] ['__abs__', '__add__', '__and__', '__class__', '__cmp__'] >>> t = (1,2,3) >>> len(dir(t)) 32 >>> dir(t)[:5] ['__add__', '__class__', '__contains__', '__delattr__', '__doc__']
As we can see, even the basic data types in Python have many attributes. We can see the first five attributes by limiting the output from “dir”;