Can dir() be called on a class?


#1

Question

In this exercise, it states that dir() can be called on an object to investigate its attributes. Can dir() also be called on a class?

Answer

Yes, you can use dir() to examine a class in addition to calling it on an object of a class. In the following code example, you can see that the dir() call on the object of class Examine shows the instance variable created in the object while the call for the class does not.

class Examine:

    class_var = "This is a class variable"

    def __init__(self):
        self.inst_var = "This is an instance variable"


myobj = Examine()

print(dir(Examine))
# OUTPUTS: ['__doc__', '__init__', '__module__', 'class_var']

print(dir(myobj))
# OUTPUTS: ['__doc__', '__init__', '__module__', 'class_var', 'inst_var']