Let's say you have a class Person
class Person:
name = "Samuel"
age = 50
country = "India"
def method1(self):
print("Method 1")
print(dir(Person))
The output of the above program looks like this:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__',
'age', 'country', 'method1', 'name']
What you can see from the above output is that it returns a sorted list of valid attributes for that object. If you look at the class Person:
name, age, country
are attributes and method1 is the method of that class. Hence when you use dir(Person), it will display all the attributes of that class.
The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:
- If the object is a module object, the list contains the names of the module’s attributes.
- If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
- Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
For example,
a = [1,2,3,45]
print(dir(a))
This will print:
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__init_subclass__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
'__setattr__', '__setitem__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend',
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Here, you can see few other attributes names insert, pop, remove etc. If you check with previous list, they were not present. It's because different types of objects have different attributes and with these attributes you can use these objects in different forms.
You can use a.pop(2)
to remove an element etc.
len I assume refers to len()
Generally, len()
is the public interface you use to get the length of an object. The __len__
method is the implementation that an object that supports the concept of length is expected to implement. len()
calls __len__()
I think I see some member functions in the returned list of attributes, len I assume refers to len(), but what are all these other things listed?
Visit the following link, https://docs.python.org/3.6/reference/datamodel.html#object.dir. Majority of them are listed here. There usages are also described.