python-vars/dir

官方中英文解释:

  • vars:返回具有__dict__属性的模块、类、实例或任何其他对象的__dict__属性。Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

  • dir:如果对象具有名为的__dir__()方法,则将调用此方法并且必须返回属性列表。如果对象未提供__dir__(),则该函数会尽力从对象的__dict__属性(如果已定义)和类型对象中收集信息。If the object has a method named __dir__(), this method will be called and must return the list of attributes. If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object.

个人理解:

  • vars:返回非私有属性变量-值,不包括方法

  • dir:返回所有属性,包括方法,(如果不重写该魔法函数)

例子:


import json

class A(object):
    def __init__(self):
        self.b = 'c'
        self.a = None
    def self_method(self):
        self.m = None
    def __repr__(self):
        print('vars : ', vars(self))
        print('dir : ', dir(self))
        return str(self.__class__) + ' : ' + json.dumps(vars(self), sort_keys=True, indent=4)

obj = A()

__repr__为交互式或print时候的打印值


>>> print(obj)
vars : {'a': None, 'b': 'c'}
dir : ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'self_method']
 : {
    "a": null, 
    "b": "c"
}

>>> print(vars(obj))
{'a': None, 'b': 'c'}

>>> print(dir(obj))

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'self_method']

调用函数后


>>> obj.self_method()
>>> print(obj)

vars : {'a': None, 'b': 'c', 'm': None}
dir : ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'm', 'self_method']
 : {
    "a": null, 
    "b": "c", 
    "m": null
}
>>> print(vars(obj))

{'a': None, 'b': 'c', 'm': None}
>>> print(dir(obj))

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'm', 'self_method']

先做记录,如果之后发现理解有误,再更改。

pass

你可能感兴趣的:(python-vars/dir)