Can dir() be called on a class?

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']
7 Likes

Why when print(dir(Examine)),'inst_var' is not listed in there???

Hi @vickytian4068895214,

When executed, the __init__ method in the example creates a variable, inst_var, that is only part of the instance that is being created. It is not part of the Examine class.

For the __init__ method to create an object that is part of the Examine class, it would need to do something like this:

    def __init__(self):
        self.inst_var = "This is an instance variable"
        # creating a new class variable
        Examine.new_class_variable = "new_class_variable"

Then after the first instance of the class is created, the Examine class would have a class variable, new_class_variable. Be careful, however, when writing code wherein an instance of a class modifies the class itself.

It will show instance variable.