Difference between dir(…) and vars(…).keys() in Python?

前端 未结 3 2139
余生分开走
余生分开走 2020-12-07 08:59

Is there a difference between dir(…) and vars(…).keys() in Python?

(I hope there is a difference, because otherwise this would break the \"

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 09:44

    Python objects store their instance variables in a dictionary that belongs to the object. vars(x) returns this dictionary (as does x.__dict__). dir(x), on the other hand, returns a dictionary of x's "attributes, its class's attributes, and recursively the attributes of its class's base classes."

    When you access an object's attribute using the dot operator, python does a lot more than just looking up the attribute in that objects dictionary. A common case is when x is an object of class C and you call a method m on it.

    class C(object):
        def m(self):
            print "m"
    
    x = C()
    x.m()
    

    The method m is not stored in x.__dict__. It is an attribute of the class C. When you call x.m(), python will begin by looking for m in x.__dict__, but it won't find it. However, it knows that x is an instance of C, so it will next look in C.__dict__, find it there, and call m with x as the first argument.

    So the difference between vars(x) and dir(x) is that dir(x) does the extra work of looking in x's class (and its bases) for attributes that are accessible from it, not just those attributes that are stored in x's own symbol table. In the above example, vars(x) returns an empty dictionary, because x has no instance variables. However, dir(x) returns

    ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
    '__hash__', '__init__', '__module__', '__new__', '__reduce__',
    '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'm']
    

提交回复
热议问题